如何从容器内部检查另一个容器是否正在端口上运行
我同时运行2个容器(通过docker-compose连接在设置链接上& amp; depters_on)。 依赖性还不够,因此我希望在一个容器的入口手机上运行的脚本检查其他容器是否已经在某些端口上运行。
我尝试了:
#!bin/bash
until nc -z w10 <container_name> 3306
do
echo waiting for db to be ready...
sleep 2
done
echo code is ready
但这是不起作用的..
有人有一个主意吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用
依赖性
方法。但是,您可以使用此命令的一些高级设置。 “ https://docs.docker.com/compose/startup-order/”的文档。请阅读 wait-for-it.sh 脚本以准确实现所需的目标。从文档中提取:
I would suggest to use the
depends_on
approach. However, you can use some of the advanced setting of this command. Please, read the documentation of Control startup and shutdown order in ComposeYou can use the wait-for-it.sh script to exactly achieve what you need. Extracted from the documentation:
由于您已经在使用 docker-compose 来编排您的服务,更好的方法是使用
depends_on
长语法的条件:service_healthy
。因此,docker-compose 不会在一个容器中手动等待另一个容器变得可用,而只会在后者变得健康之后才启动前者,即可用的。如果依赖的容器没有指定的
HEALTHCHECK
在其图像中,您已经可以在docker-compose.yml
中使用healthcheck
属性。使用包含的 mariadb 数据库示例>
healthcheck.sh
脚本:使用这个
docker-compose up
会首先启动db
服务,并等待db
服务变得healthy
,即准备好接受连接,并且只然后将启动app
服务,该服务可以立即连接到db
。Since you are already using
docker-compose
to orchestrate your services a better way would be to usecondition: service_healthy
of thedepends_on
long syntax. So instead of manually waiting in one container for the other to become availabledocker-compose
will start the former only after the latter becamehealthy
, i.e. available.If the depended-on container does not have a specified
HEALTHCHECK
in its image already you can manually define it in thedocker-compose.yml
with thehealthcheck
attribute.Example with a
mariadb
database using the includedhealthcheck.sh
script:With this
docker-compose up
will first start thedb
service and wait until thedb
service becomeshealthy
, i.e. is ready to accept connections, and only then will start theapp
service which can immediately connect to thedb
.