Checking if the Postgres service of a Docker container is ready

Published on 2020-08-30 • Modified on 2020-08-30

In this snippet, we will see how to wait for the Postgres service to be available before using it. It's to avoid the following kind of errors: An exception occurred in driver: SQLSTATE[08006] [7] server closed the connection unexpectedly. So, before using Doctrine, like creating the database and loading the fixtures, we will call the following bash script (On can name it wait-for-postgres.sh). It will run the pg_isready executable until it returns OK. Then the execution of the script will continue. In a makefile, it must be called just after the docker-compose up. Replace phpquiz-postgres by the name of your Docker container. I am using this in the phpquiz project, check out the public GitHub repository.


#!/bin/sh
# https://stackoverflow.com/q/46516584/633864
until docker container exec -it phpquiz-postgres pg_isready; do
    >&2 echo "Postgres is unavailable - waiting for it... 😴"
sleep 1
done

 More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil