1

I am trying to start one container after the MySQL one is initialized.

This was not an issue in docker-compose v2.1 In the version 3 of docker-compose the depends-on doesn't have the condition statement anymore.

My current setup looks like this:

test:
    image: php:7.2
    container_name: second
    restart: on-failure
    depends_on:
        - mysql-test

mysql-test:
    image: mysql:5.7
    container_name: first
    environment:
        MYSQL_ROOT_PASSWORD: secret
    healthcheck:
        test: ["CMD", "mysqladmin", "ping", "-psecret", "-h", "localhost"]
        timeout: 30s
        retries: 10

Of course, running docker-compose up and then executing script in the PHP container that is trying to connect to the database results in SQLSTATE[HY000] [2002] Connection refused since MySQL container is not ready yet.

Is there a recommended approach to this problem in docker-compose version 3 or any kind of a workaround?

Jan Richter
  • 1,976
  • 4
  • 29
  • 49

1 Answers1

0

We have achieved this with a custom ENTRYPOINT in our Docker image.

This is a shell script that is used as the entrypoint. It contains some Python code to check if database is alive, but it should be similar with PHP. The script loops until it is able to successfully connect to the database, and after that (in the exec line) runs the CMD from the Dockerfile.

#!/bin/bash
set -e

function db_ready(){
python << END
import sys
import sqlalchemy

try:
    engine_pro = sqlalchemy.create_engine("${DATABASE}").connect()
except (sqlalchemy.exc.SQLAlchemyError, sqlalchemy.exc.DBAPIError) as e:
    print('Error:', e)
    sys.exit(-1)
sys.exit(0)
END
}

until db_ready; do
  >&2 echo 'Waiting for database to become available...'
  sleep 1
done
>&2 echo 'Database is available'

exec "$@"

You need to save this script in a file and set it as your entrypoint for your test service in the docker-compose.yml.

Mikhail Burshteyn
  • 4,762
  • 14
  • 27
  • 1
    I am trying to avoid this. Having one image with explicit definition to the other one (even though `DATABASE` is replaceable). What if I will introduce the whole stack of databases that I am relying on, then this script grows enormously. I think there should be a native way for `docker-compose` to manage this since docker already tracks the status of health checks so compose could just wait. – Jan Richter Aug 30 '18 at 20:59