问题
docker-compose
配置容器启动顺序,有时依靠depends_on
并不能完全解决,主要原因是:
depends_on
只能保证容器进入了running
状态,而不保证进入ready
状态.- Control startup and shutdown order in Compose
解决方案
启动命令前增加判断依赖服务状态的工具
示例:
version: "2"
services:
web:
build: .
ports:
- "80:8000"
depends_on:
- "db"
command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"]
db:
image: postgres
自己编写script
#!/bin/sh
# wait-for-postgres.sh
set -e
host="$1"
shift
cmd="$@"
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec $cmd
测试:
command: ["./wait-for-postgres.sh", "db", "python", "app.py"]
wait-for命令测试
- 下载wait-for
[root@node1 ~]# chmod a+x wait_for
[root@node1 ~]# ./wait_for localhost:3306 -- echo "Mysql site is up"
Eficode site is up