我如何等待Docker容器启动并运行? [英] How can I wait for a docker container to be up and running?

查看:651
本文介绍了我如何等待Docker容器启动并运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在容器内运行服务时,假设使用mongodb命令

When running a service inside a container, let's say mongodb, the command

docker run -d myimage

将立即退出,并返回容器ID. 在我的CI脚本中,我在运行mongo容器之后立即运行客户端以测试mongodb连接. 问题是:由于服务尚未启动,客户端无法连接. 除了在脚本中添加大sleep 10之外,我没有看到等待容器启动并运行的任何选项.

will exit instantly, and return the container id. In my CI script, I run a client to test mongodb connection, right after running the mongo container. The problem is: the client can't connect because the service is not up yet. Apart from adding a big sleep 10in my script, I don't see any option to wait for a container to be up and running.

Docker的命令wait在这种情况下不起作用,因为该容器不存在. 是docker的限制吗?

Docker has a command wait which doesn't work in that case, because the container doesn't exist. Is it a limitation of docker?

推荐答案

HEALTHCHECK支持根据 docker/docker#23218 合并到上游可以考虑先确定容器何时健康,然后再按顺序开始下一个容器

HEALTHCHECK support is merged upstream as per docker/docker#23218 - this can be considered to determine when a container is healthy prior to starting the next in the order

docker 1.12rc3(2016-07-14)开始可用

docker-compose正在支持支持以下功能的功能等待特定条件.

docker-compose is in the process of supporting a functionality to wait for specific conditions.

它使用libcompose(因此我不必重建docker交互),并为此添加了一堆配置命令.在此处查看: https://github.com/dansteen/control-compose

It uses libcompose (so I don't have to rebuild the docker interaction) and adds a bunch of config commands for this. Check it out here: https://github.com/dansteen/controlled-compose

您可以像这样在Dockerfile中使用它:

You can use it in Dockerfile like this:

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

官方文档: https://docs.docker.com/engine/reference /builder/#/healthcheck

这篇关于我如何等待Docker容器启动并运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆