I have a standard Python docker image that needs to start after postgers is properly started in its standard image.
I understand that I can add this Bash command in the docker-compose file:
command: bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; npm start'
depends_on:
- mypostgres
But I don't have bash installed in the standard python docker image, and I'm trying to keep the installation minimal.
Is there a way to wait for postgres without having bash installed in my image?
CodePudding user response:
I have a standard Python docker image that needs to start after postgres is properly started in its standard image.
You mentioned "Python docker image", but you appear to be calling npm start
, which is a node.js application, not a Python application.
The standard Python images do have bash
installed (as do the official Node images):
$ docker run -it --rm python:3.10 bash
root@c9bdac2e23f9:/#
However, just checking for the port to be available may be insufficient in any case, so really what you want is to execute a query against the database and only continue once the query is successful.
A common solution is to install the postgres cli and run psql
in a loop, like this:
until psql -h $HOST -U $USER -d $DB_NAME -c 'select 1' >/dev/null 2>&1; do
echo 'Waiting for database...'
sleep 1
done
You can use environment variables or a .pgpass
file to provide the appropriate password.
If you are building a custom image, it may be better to place this logic in your ENTRYPOINT
script rather than embedding it in the command
field of your docker-compose.yaml
.
If you don't want to psql
, you can write the same logic in Python or Node utilizing whatever Postgres bindings are available (e.g., something like psycopg2
for Python).
A better solution is to make your application robust in the face of database failures, because this allows your application to continue running if the database is briefly unavailable during a restart.