Reputation: 353
I am super embarrassed to ask this question, because it seems a very basic one, but somehow I can't find the answer in docs.
I have a django app that uses postgres. In docker-compose.yaml
there is the following requirement:
version: "2"
services:
database:
image: postgres:9.5
environment:
POSTGRES_DB: ${POSTGRES_DATABASE}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DATA: /var/lib/postgresql/data/pgdata
when I run my docker image:
docker run -it --name myapp myimage
it keeps repeating:
The database is not ready.
wait for postgres to start...
I ran postgres in detached mode: docker run -it -d postgres:9.5
but it does not help
Upvotes: 2
Views: 1550
Reputation: 9759
With Docker Compose 2.1 syntax, you can specify healthchecks to control container start-up:
version: '2.1'
services:
application:
depends_on:
database:
condition: service_healthy
Check out https://github.com/docker-library/healthcheck/tree/master/postgres for an example Dockerfile for building Postgres with healthchecks.
Upvotes: 3
Reputation: 22595
Please have a look at this doc.
Second example is exacly what you need:
You create sh script and add it to your app container by using ADD
or COPY
:
#!/bin/bash
# wait-for-postgres.sh
set -e
host="$1"
shift
cmd="$@"
until psql -h "$host" -U "postgres" -c '\l'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec $cmd
Then you modify your docker-compose.yaml like this:
version: "2"
services:
web:
build: .
ports:
- "80:8000"
depends_on:
- "db"
command: ["./wait-for-postgres.sh", "db", "python", "app.py"]
db:
image: postgres
In command
you're orerriding default command of your container.
Of course "python", "app.py"
part is depedent on how you start your app.
Fo Java it would be for example "java", "-jar", "my-app.jar"
etc.
Upvotes: 1
Reputation: 3185
Everything is OK with the way you start the container, however, the issues you are experiencing it is because the DB and the APP containers are starting one after the other, however, the DB container, needs to prepare the DB, do the migrations and so on, so therefore, by the time your app container tries to reach your DB container it is not ready so that's why you are getting this error.
You have 2 choices, one is to edit your APP Dockerfile and add WAIT for 30 - 60 s or so, or you could just start the DB on its own, wait for it to be ready to go and then start your APP container.
Upvotes: 0