Docker 中的容器一般都会遇到相互之间服务依赖的问题, 通过 --link 指定一个或多个依赖容器服务, 但启动的时候却因为容器内的服务启动的延时不确定, 并不能保证所有容器都能成功启动, 于是需要强制按容器内的服务顺序来启动容器.

需要一个工具:
wait-for-it.sh
https://github.com/vishnubob/wait-for-it

先下载这个脚本, 然后根据项目中容器的服务依赖顺序配置就可以了, 唯一的问题就是服务都需要有可访问的端口.

举个栗子:

nginx 依赖 php-fpm 依赖 redis | mysql

那么就倒序启动, web_up.sh

wait_for_it=/zzstore/my-tools/wait-for-it/wait-for-it.sh
docker container start my-mysql-8.0 && \
$wait_for_it -s -t 15 localhost:16033 -- echo 'mysql is up ~'       && docker container start redis-6.2-19736 && \
$wait_for_it -s -t 15 localhost:19736 -- echo 'redis-19736 is up ~' && docker container start redis-6.2-19740 && \
$wait_for_it -s -t 15 localhost:19740 -- echo 'redis-19740 is up ~' && docker container start my-php-8.0-fpm  && \
$wait_for_it -s -t 15 localhost:9080  -- echo 'php-fpm is up ~'     && docker container start my-nginx-1.20   && \
$wait_for_it -s -t 15 localhost:80    -- echo 'nginx is up ~'

-s: 表示严格模式, 若检测的服务在 -t: xx秒 内没有启动, 则终止后续所有命令.

这个脚本是在宿主机上运行的, 监听的端口也都是宿主机上的端口, 如: 16033 映射 mysql 容器内 3306

也可以用来监听 Docker 服务的启动状态:

wait_for_it=/zzstore/my-tools/wait-for-it/wait-for-it.sh
$wait_for_it -s -t 60 localhost:2375  -- echo 'docker is up ~'      && docker container start my-mysql-8.0    && \
$wait_for_it -s -t 15 localhost:16033 -- echo 'mysql is up ~'       && docker container start redis-6.2-19736 && \
$wait_for_it -s -t 15 localhost:19736 -- echo 'redis-19736 is up ~' && docker container start redis-6.2-19740 && \
$wait_for_it -s -t 15 localhost:19740 -- echo 'redis-19740 is up ~' && docker container start my-php-8.0-fpm  && \
$wait_for_it -s -t 15 localhost:9080  -- echo 'php-fpm is up ~'     && docker container start my-nginx-1.20   && \
$wait_for_it -s -t 15 localhost:80    -- echo 'nginx is up ~'

等 Dockerd 服务启动后自动按服务顺序启动所有容器.

至于 -t 参数的时长可以在服务器上先测试一下根据实际情况再调整下.

全部正常成功启动的效果图:

Docker多容器link连接后按顺序启动容器
上面的启动命令每个 -- 后的所有命令都是一个整体, 前面没有执行成功后面都不会触发.

再来测试下启动失败的情况:

当前容器全部已启动的状态, 我们关闭其中一个依赖的服务 redis-6.2-19740 然后再执行脚本.

docker container stop redis-6.2-19740
wait_for_it=/zzstore/my-tools/wait-for-it/wait-for-it.sh
$wait_for_it -s -t 60 localhost:2375  -- echo 'docker is up ~'      && docker container start my-mysql-8.0    && \
$wait_for_it -s -t 15 localhost:16033 -- echo 'mysql is up ~'       && docker container start redis-6.2-19736 && \
#$wait_for_it -s -t 15 localhost:19736 -- echo 'redis-19736 is up ~' && docker container start redis-6.2-19740 && \
$wait_for_it -s -t 15 localhost:19740 -- echo 'redis-19740 is up ~' && docker container start my-php-8.0-fpm  && \
$wait_for_it -s -t 15 localhost:9080  -- echo 'php-fpm is up ~'     && docker container start my-nginx-1.20   && \
$wait_for_it -s -t 15 localhost:80    -- echo 'nginx is up ~'

在这里插入图片描述

wait-for-it.sh: timeout occurred after waiting 15 seconds for localhost:19740
wait-for-it.sh: strict mode, refusing to execute subprocess

由于 redis-6.2-19740 没有启动, 而且使用了 -sstrict mode 因此后续存在依赖的命令全都不会执行了.

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐