0%

docker-compose配置依赖和启动顺序

问题

docker-compose配置容器启动顺序,有时依靠depends_on并不能完全解决,主要原因是:

解决方案

启动命令前增加判断依赖服务状态的工具

示例:

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命令测试

[root@node1 ~]# chmod a+x wait_for 
[root@node1 ~]# ./wait_for localhost:3306 -- echo "Mysql site is up"
Eficode site is up