仅在首次启动时在Docker容器中运行命令 [英] Run command in Docker Container only on the first start

查看:761
本文介绍了仅在首次启动时在Docker容器中运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用脚本( / bin / bash /init.sh )作为入口点的Docker映像。我只想在容器的第一次启动时执行此脚本。在docker守护进程崩溃后重新启动或重新启动容器时,应将其省略。

I have a Docker Image which uses a Script (/bin/bash /init.sh) as Entrypoint. I would like to execute this script only on the first start of a container. It should be omitted when the containers is restarted or started again after a crash of the docker daemon.

是否可以使用docker本身来执行此操作,或者在脚本中实现某种检查?

Is there any way to do this with docker itself, or do if have to implement some kind of check in the script?

推荐答案

我遇到了同样的问题,这里有一个简单的过程(即解决方法)解决它:

I had the same issue, here a simple procedure (i.e. workaround) to solve it:

步骤1:

创建一个 myStartupScript.sh包含以下代码的脚本:

Create a "myStartupScript.sh" script that contains this code:

CONTAINER_ALREADY_STARTED="CONTAINER_ALREADY_STARTED_PLACEHOLDER"
if [ ! -e $CONTAINER_ALREADY_STARTED ]; then
    touch $CONTAINER_ALREADY_STARTED
    echo "-- First container startup --"
    # YOUR_JUST_ONCE_LOGIC_HERE
else
    echo "-- Not first container startup --"
fi

步骤2:

将#YOUR_JUST_ONCE_LOGIC_HERE行替换为仅在首次启动容器时要执行的代码

Replace the line "# YOUR_JUST_ONCE_LOGIC_HERE" with the code you want to be executed only the first time the container is started

步骤3 :

将脚本设置为Dockerfile的入口点:

Set the scritpt as entrypoint of your Dockerfile:

ENTRYPOINT ["/myStartupScript.sh"]

总而言之,逻辑很简单,它检查文件系统中是否存在特定文件;如果没有,它将创建它并执行一次代码。下次启动容器时,文件位于文件系统中,因此代码不会执行。

In summary, the logic is quite simple, it checks if a specific file is present in the filesystem; if not, it creates it and executes your just-once code. The next time you start your container the file is in the filesystem so the code is not executed.

这篇关于仅在首次启动时在Docker容器中运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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