I have two Docker Compose files: one for database containers and the other for application containers. I want to ensure that whenever the machine restarts, the containers automatically restart. Additionally, I need the database containers to restart first, followed by the application containers. How can I achieve this with Docker Compose?
By adding restart: always
, the services will automatically restart. However, I want to ensure that the services defined in docker-compose-db.yaml
and docker-compose-app.yaml
start in a specific order, with docker-compose-db.yaml
always starting first when the machine restarts.
Have you tried depends_on
?
I tried, but in the second docker-compose.yml
file, it is unable to access the database service because the database service is created by a separate docker-compose.yml
file.
Here is the log:
service “app” depends on undefined service “db”: invalid compose project
compose.yml
include:
- path:
- docker-compose-db.yaml
- path:
- docker-compose-app.yaml
This would treat them as a single file
Though perhaps setting the includes
property within docker-compose-app.yaml
is a better approach
That is because app relies on db existing and will simply not work without it
I have a question regarding this: If I stop the docker-compose-app.yaml
file, will the database services also stop, or will they continue running?
If you include the db compose within the app compose file, it is as if the services were written right there in the same file
docker compose down
applies to all services without profiles defined, so yes
You can specify service profiles, or service names in the compose commands to act on specific ones
I assume this is already the case, but I am still going to ask
Did you also use the restart: true
setting in the depends_on
block of the app?
services:
app:
...
depends_on:
db:
condition: service_healthy
restart: true
db:
...
This will make sure a restart of db, restarts the app as well.
I want to separate the database and application configurations into two YAML files. Additionally, I would like to add depends_on
and restart
configurations.