How to make a container wait for other container

Hello folks,

I have a container with a database, and then 5 other containers that require the db in orde to function. Currently the loading times when reinitialising the device are atrocious because 4 containers are constantly complaining that the db isnt up and running, and thereby causing the db startup to run even slower. Isn’t there some way to get the others to wait until the db is up, running and healthy before they continue? Maybe I need to get the db container to write something to a file that the others should check? It seems that there is only limited function of using the ‘depends on’ feature in docker compose.

Hi,

The depends_on only checks whether a container A is running before starting container B.
It has no knowledge of the state of anything running within container A.

I think the best you can do, is to wrap your application in a script that checks whether or not the database is actually reachable before running your actual application.

Something like this.

#!/bin/bash

let db_ok=0
for (( attempt = 0 ; attempt < 10 ; attempt++ )); do
  mysql --user=${DB_USER} --password=${DB_PASS} --host=${DB_CONTAINER_NAME} --silent --connect-timeout=10 --execute="exit"
  if [ $? -eq 0 ]; then
    db_ok=1;
    break;
  fi
done

if [ $db_ok -eq 1 ]; then
  # Run application
else
  # Failed to connect
  exit 1
fi

Of course, you should swap out the mysql line for whatever test you want to do.

1 Like

thanks, this is what I’m doing already currently - I’ll stick with it for now.

I ran into the same issue. It would be nice if balena’s compose implementation supported the service_healthy and healthcheck options but unfortunately it’s limited to just service_started.

-mike

1 Like

Hello @mpilone we are working to improve this. In the meantime we have a public roadmap lead by our community and it could be great to have your use case described here.

I could find this example that i think it’s similar → Service dependencies · Balena Roadmap

1 Like

Will do. Thanks for pointing that out.

-mike

1 Like