LoginSignup
76
75

More than 3 years have passed since last update.

docker-compose を CI で実行するとき, MySQL の起動完了まで確実に待つ

Last updated at Posted at 2020-01-18

背景

この辺は全部試したが, PHP から接続しようとすると Connection Refused が多発する。TCP で接続可能になってから実際に利用可能になるまで若干のラグがあるため,もっと確実な方法を探していた。

対処法

とりあえずこれを書いておけ
sh -c 'docker-compose logs -f <MySQLコンテナ名> | { sed "/\[Entrypoint\]: MySQL init process done\. Ready for start up\./ q" && kill $$ ;}' >/dev/null 2>&1 || :
YAMLのリストに書く場合はエスケープが必要なのでパイプから改行する
- |
  sh -c 'docker-compose logs -f <MySQLコンテナ名> | { sed "/\[Entrypoint\]: MySQL init process done\. Ready for start up\./ q" && kill $$ ;}' >/dev/null 2>&1 || :

ログを見れば確実!ログに MySQL init process done と出ればアプリケーションレベルでも必ず有効な状態であることが保証される。

おまけ

php-fpm 版
sh -c 'docker-compose logs -f <FPMコンテナ名> | { sed "/NOTICE: ready to handle connections/ q" && kill $$ ;}' >/dev/null 2>&1 || :
あわせ技(その1)
sh -c 'docker-compose logs -f <MySQLコンテナ名> | { sed "/\[Entrypoint\]: MySQL init process done\. Ready for start up\./ q" && kill $$ ;}' >/dev/null 2>&1 &
sh -c 'docker-compose logs -f <FPMコンテナ名> | { sed "/NOTICE: ready to handle connections/ q" && kill $$ ;}' >/dev/null 2>&1 &
wait

引数なし wait で一気に終了を待つ場合は終了ステータスが不問になるため, || : は不要です。

あわせ技(その2)
{
  sh -c 'docker-compose logs -f <MySQLコンテナ名> | { sed "/\[Entrypoint\]: MySQL init process done\. Ready for start up\./ q" && kill $$ ;}' &
  sh -c 'docker-compose logs -f <FPMコンテナ名> | { sed "/NOTICE: ready to handle connections/ q" && kill $$ ;}' &
  wait
} >/dev/null 2>&1 

リダイレクトをまとめて見やすく。

76
75
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
76
75