本文共 2934 字,大约阅读时间需要 9 分钟。
In docker-compose a common problem is starting services and daemons in containers that depends on services running on linked containers, in example: your app depends on elasticsearch but it is not ready when the app container is started. Solution is to use a wait script.
在docker-compose中,一个常见的问题是在依赖于在链接容器上运行的服务的容器中启动服务和守护程序,例如:您的应用程序依赖于Elasticsearch,但在启动应用程序容器时尚未准备就绪。 解决方案是使用等待脚本。
I knew that docker-compose team is working on adding a WAIT parameter, but while it is not ready we can use a wait script to load our services.
我知道docker-compose团队正在努力添加WAIT参数,但是当它还没有准备好时,我们可以使用等待脚本来加载我们的服务。
The process is simple, your container will execute a shell script that will try to execute a HEALTH CHECK many times you want before starting the main command. The health check, the command, the sleep and how many loops to try will be defined in environment variables
该过程很简单,您的容器将执行一个shell脚本,该脚本将在启动main命令之前尝试多次执行一次HEALTH CHECK。 运行状况检查,命令,睡眠和尝试尝试的循环次数将在环境变量中定义
This is a program that needs to access an elasticsearch server located in ‘elastic’ host (that will be mapped by compose
这是一个程序,需要访问位于“弹性”主机中的elasticsearch服务器(该文件将通过组合
access_elastic_search.py
access_elastic_search.py
from datetime import datetime from elasticsearch import Elasticsearches = Elasticsearch('elastic')es.index(index="my-index", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()})print es.get(index="my-index", doc_type="test-type", id=42)from datetime import datetime from elasticsearch import Elasticsearches = Elasticsearch('elastic')es.index(index="my-index", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()})print es.get(index="my-index", doc_type="test-type", id=42)
docker-compose.yml
docker-compose.yml
wait_to_start
script
wait_to_start
脚本
#!/bin/bashecho $WAIT_COMMANDecho $WAIT_START_CMDis_ready() { eval "$WAIT_COMMAND"}# wait until is readyi=0while ! is_ready; do i=`expr $i + 1` if [ $i -ge $WAIT_LOOPS ]; then echo "$(date) - still not ready, giving up" exit 1 fi echo "$(date) - waiting to be ready" sleep $WAIT_SLEEPdone#start the scriptexec $WAIT_START_CMD #!/bin/bashecho $WAIT_COMMANDecho $WAIT_START_CMDis_ready() { eval "$WAIT_COMMAND"}# wait until is readyi=0while ! is_ready; do i=`expr $i + 1` if [ $i -ge $WAIT_LOOPS ]; then echo "$(date) - still not ready, giving up" exit 1 fi echo "$(date) - waiting to be ready" sleep $WAIT_SLEEPdone#start the scriptexec $WAIT_START_CMD
Now when you start your environment with docker-compose up
the app container will start and execute wait_to_start
script, which will perform the test defined in WAIT_COMMAND
environment variable and will retry until the test succeeds, so it will end executing the program defined in WAIT_START_CMD
现在,当您使用docker-compose up
启动环境docker-compose up
,应用程序容器将启动并执行wait_to_start
脚本,该脚本将执行WAIT_COMMAND
环境变量中定义的测试,并将重试直到测试成功,因此它将结束执行WAIT_START_CMD
定义的程序
翻译自:
转载地址:http://cwhwd.baihongyu.com/