Docker - check if postgres is ready
Here is a shell one liner using pg_isready
tool provided by PostgreSQL.
To call outside docker:
DOCKER_CONTAINER_NAME="mypgcontainer"timeout 90s bash -c "until docker exec $DOCKER_CONTAINER_NAME pg_isready ; do sleep 5 ; done"
I tried wait-for-it, but it may be a problem to run it in docker container as in the docker image may not be installed nc (sometimes there is not even ping, telnet, curl..). So to check if the DB is up and running I have used HealthCheck in docker compose file what was checking return value of pg_isready, what is part of postgres database, so you do not need to install anything into docker images:
version: '2.3'services: postgres-db: image: postgresImage healthcheck: test: /usr/bin/pg_isready interval: 5s timeout: 10s retries: 120 ports: - '5432:5432' aplication: image: applicationImage depends_on: postgres-db: condition: service_healthy
We solve this with a simple TCP check on port 5432, without any PG tooling. We just use wait-for-it.sh
, and it works well. Postgres does not open the port until the server is actually ready to serve, so this is apparently fine.
Sample Dockerfile: https://github.com/apim-haufe-io/wicked.kong/blob/master/Dockerfile
Corresponding start script (only the last line is interesting for this specific problem): https://github.com/apim-haufe-io/wicked.kong/blob/master/startup.sh
Snippet:
wait-for-it.sh -h $KONG_PG_HOST -p 5432 -t 30 -- kong start --run-migrations
Wait for it: https://github.com/vishnubob/wait-for-it