Docker-compose检查mysql连接是否准备就绪[版本3]

时间:2018-08-30 20:07:13

标签: mysql docker docker-compose

我试图在初始化一个MySQL容器后启动一个容器。

This was not an issue in docker-compose v2.13的{​​{1}}版本中,docker-compose doesn't have the condition statement anymore

我当前的设置如下:

depends-on

当然,由于MySQL容器尚未准备好,因此在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 中运行docker-compose up然后在试图连接数据库的PHP容器中执行脚本会导致SQLSTATE[HY000] [2002] Connection refused

docker-compose第3版中是否存在针对此问题的推荐方法或其他解决方法?

1 个答案:

答案 0 :(得分:0)

我们已经在Docker映像中通过自定义ENTRYPOINT实现了这一目标。

这是一个shell脚本,用作入口点。它包含一些Python代码来检查数据库是否还处于活动状态,但它与PHP应该相似。该脚本将循环运行,直到能够成功连接到数据库为止,然后(在exec行中)从Dockerfile运行CMD

#!/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 "$@"

您需要将此脚本保存到文件中,并将其设置为entrypointtest服务的docker-compose.yml