问题描述
我有一个领事docker映像,它是 docker-compose
环境的一部分.
I have a consul docker image which is a part of a docker-compose
environment.
我必须在docker容器中运行命令 consul acl bootstrap
,我相信在 command
或 entrypoint
中提及它会覆盖默认值为领事设置的命令,除默认命令外,我还应如何执行?
I have to run the command consul acl bootstrap
inside the docker container, I believe mentionining it in command
or entrypoint
will override the default commands set for consul, how do I execute it in addition to the default commands?
推荐答案
在docker-compose中没有选项允许您在启动容器后运行命令.
There is no option in docker-compose to allow you to run a command after a container is started.
您可以做的是构建自己的映像,该映像将在启动时执行所需的操作.为此,您需要:
What you can do is to build your own image that will execute the actions you want on startup. To do this you need to:
- 找出容器的默认启动方式(
ENTRYPOINT
和CMD
组合). - 创建一个shell脚本,该脚本将使用所需的参数调用入口点,然后它将调用您的命令.
- 创建基于原始映像的Dockerfile,在映像中复制shell脚本,并将入口点更改为您的脚本
- 将您的映像和dockerfile添加到docker-compose(更改当前领事映像以指向您的映像并构建脚本)
这里是入口点外壳脚本的示例,可用于启动特定脚本.将您的代码放在 execute_after_start()
函数中.
Here is example of a entrypoint shell script what can be used to kickstart your specific script. Place your code in the execute_after_start()
function.
entrypoint.sh
#!/bin/bash
set -e
execute_before_start() {
echo "Execute befor start" > /running.txt
}
execute_after_start() {
sleep 1
echo "Execute after start" >> /running.txt
}
execute_before_start
echo "CALLING ENTRYPOINT WITH CMD: $@"
exec /old_entrypoint.sh "$@" &
daemon_pid=$!
execute_after_start
wait $daemon_pid
echo "Entrypoint exited" >> running.txt
该脚本将启动 execute_before_start
.该命令结束后,将使用与 CMD
一起提供的参数并平行地开始原始入口点(这是 execute &
/code>),它将开始 execute_after_start
.当 execute_after_start
完成时,它将等待原始入口点停止.
The script will start the execute_before_start
. When this commands are over, will start the original entry point with the arguments provided with CMD
and in parallel (this is the &
at the end of execute
) it will start execute_after_start
. When execute_after_start
is over, it will wait for the original entry point to stop.
在示例中,我使用 sleep
作为确保延迟的简单方法,以便入口点可以接收命令.根据入口点的不同,可能会有更聪明的方法来确保入口点已准备好接受命令.
I use sleep
in the example as a simples way to assure some delay so the entry point can take the commands. Depending on the entrypoint, there might be smarter ways to assure that the entrypoint is ready to take the commands.
这篇关于当Docker映像运行时如何运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!