I am running 2 containers at the same time (connected via docker-compose on setting links && depends_on). The depends on is not enough, so I want the script that run on entryphone of one of the container to check if the other container is running already on some port.
I tried:
#!bin/bash
until nc -z w10 <container_name> 3306
do
echo waiting for db to be ready...
sleep 2
done
echo code is ready
But this is not working..
Anyone got an idea?
CodePudding user response:
I would suggest to use the depends_on
approach. However, you can use some of the advanced setting of this command. Please, read the documentation of Control startup and shutdown order in Compose
You can use the wait-for-it.sh script to exactly achieve what you need. Extracted from the documentation:
version: "2"
services:
web:
build: .
ports:
- "80:8000"
depends_on:
- "db"
command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"]
db:
image: postgres
CodePudding user response:
Since you are already using docker-compose
to orchestrate your services a better way would be to use condition: service_healthy
of the depends_on
long syntax. So instead of manually waiting in one container for the other to become available docker-compose
will start the former only after the latter became healthy
, i.e. available.
If the depended-on container does not have a specified HEALTHCHECK
in its image already you can manually define it in the docker-compose.yml
with the healthcheck
attribute.
Example with a mariadb
database using the included healthcheck.sh
script:
services:
app:
image: myapp/image
depends_on:
db:
condition: service_healthy
db:
image: mariadb
environment:
- MARIADB_ROOT_PASSWORD=password
healthcheck:
test: "healthcheck.sh --connect"