You could use depends on, e.g.
version: "3.9"
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
But:
depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.
For controlling startup order
, you need explicitly write script to wait other container starts to work, e.g. if you want to make sure a db container really starts, you could let the app container connect to the db container to have try. If link successful, means the db container starts, otherwise, loop to try again.
E.g. example extract from above documention:
- Use a tool such as wait-for-it, dockerize, sh-compatible wait-for, or RelayAndContainers template. These are small wrapper scripts which
you can include in your application’s image to poll a given host and
port until it’s accepting TCP connections.
For example, to use wait-for-it.sh or wait-for to wrap your service’s
command:
version: "2"
services: web:
build: .
ports:
- "80:8000"
depends_on:
- "db"
command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"] db:
image: postgres
- Alternatively, write your own wrapper script to perform a more
application-specific health check. For example, you might want to wait
until Postgres is ready to accept commands:
#!/bin/sh
# wait-for-postgres.sh
set -e
host="$1"
shift
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec "$@"
You can use this as a wrapper script as in the previous example, by setting:
command: ["./wait-for-postgres.sh", "db", "python", "app.py"]
Finally,
Can easily be composed down with simple ctrl+c?
I think docker-compose down
is not so complex, isn't it?