Dockerfile CMD 指令将在运行后立即退出容器 [英] Dockerfile CMD instruction will exit the container just after running it

查看:182
本文介绍了Dockerfile CMD 指令将在运行后立即退出容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的容器启动时设置一些配置,为此我使用的是 shell 脚本.但是我的容器将在我的脚本结束后立即退出,我尝试使用 -d 标志/分离模式,但它永远不会在分离模式下运行.

I want to setup some configuration when my container starts, for this I am using shell scripts. But my container will exits as soon as my scripts ends, I have tried with -d flag / detached mode but It will never run in detached mode.

下面是我的 Dockerfile

Below is my Dockerfile

FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh

下面是我的shell脚本

Below is my shell script

#!/bin/bash
echo Hello-docker

  1. 不带任何标志运行

  1. Run without any flag

docker run hello-docker

这将在我的控制台上打印Hello-docker"并退出

This will print 'Hello-docker' on my console and exits

使用 -itd 标志运行

Run with -itd flags

docker run -itd hello-docker

如下所示,我的控制台输出,这一次也将很快退出.:(

and as below my console output, This time also will exits soon. :(

  • 我在 COMMAND 部分看到的不同之处在于,当我运行其他图像时,命令部分将显示/bin/bash",并将继续以分离模式运行.

  • The difference I saw is in COMMAND section when I run other images command section will shows "/bin/bash" and will continue in detached mode.

当我使用 shell 脚本在容器中运行我的图像时,COMMAND 部分将显示/bin/sh -c/usr/loca",然后退出.

And when I run my image in container with shell script COMMAND section will show "/bin/sh -c /usr/loca", and Exit.

我想运行容器直到我不手动停止它.

I want to run container till I not stop it manually.

在 Dockerfile 中添加 ENTRYPOINT 指令后,这将不会执行我的 shell 脚本 :(

After adding ENTRYPOINT instruction in Dockerfile, this will not execute my shell script :(

FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh

ENTRYPOINT /bin/bash

根据 docker 文档 这里

As per docker documentation here

当使用替代参数运行容器时,CMD 将被覆盖,因此如果我使用以下一些参数运行 docker image,将不会执行 CMD 指令.:(

CMD will be overridden when running the container with alternative arguments, so If I run docker image with some arguments as below, will not execute CMD instructions. :(

sudo docker run -it --entrypoint=/bin/bash <imagename>

推荐答案

最后通过一些实验,我得到了最好的结果,如下所示

Finally with some experiments I got my best result as below

我的 Dockerfile 没有任何问题,如下所示是正确的.

There is nothing wrong with my Dockerfile as below it's correct.

FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh

为了得到预期的结果,我只需在我的 shell 脚本文件中添加一个命令(/bin/bash),如下所示,然后一切都以我最好的方式运行.

What I do to get expected result is, I just add one more command(/bin/bash) in my shell script file as below and vola everything works in my best way.

#!/bin/bash

echo "Hello-docker" > /usr/hello.txt

/bin/bash

这篇关于Dockerfile CMD 指令将在运行后立即退出容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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