我已经看到了一堆教程,似乎做同样的事情,我试图做,但出于某种原因,我的Docker容器退出。基本上,我在Docker容器中设置了一个web服务器和几个守护进程。我通过一个名为run-all.sh的bash脚本来完成最后的部分,我在Dockerfile中通过CMD运行该脚本。Run-all.sh看起来像这样:

service supervisor start
service nginx start

我在Dockerfile中启动它,如下所示:

CMD ["sh", "/root/credentialize_and_run.sh"]

我可以看到,当我手动运行(即使用-t /bin/bash进入映像)时,所有服务都正确启动,并且当我运行映像时,一切看起来都正确运行,但一旦它完成启动我的进程,它就退出了。我希望进程无限期地运行,据我所知,容器必须一直运行才能实现这一点。然而,当我运行docker ps -a时,我看到:

➜  docker_test  docker ps -a
CONTAINER ID        IMAGE                            COMMAND                CREATED             STATUS                      PORTS               NAMES
c7706edc4189        some_name/some_repo:blah   "sh /root/run-all.sh   8 minutes ago       Exited (0) 8 minutes ago                        grave_jones

到底发生了什么事?为什么它令人兴奋?我知道我可以在bash脚本的末尾放一个while循环来保持它,但是怎样才能使它不退出呢?


当前回答

你可以像兄弟@Sa'ad提到的那样,不带任何参数地运行plain cat,简单地让容器工作(实际上什么都不做,只是等待用户输入)(Jenkins的Docker插件也做同样的事情)

其他回答

在一个变量(例如$NGNIX_PID)中捕获ngnix进程的PID,并在入口点文件do的末尾

wait $NGNIX_PID 

通过这种方式,容器应该一直运行到ngnix激活,当ngnix停止时,容器也会停止

如果您正在使用Dockerfile,请尝试:

ENTRYPOINT ["tail", "-f", "/dev/null"]

(显然这只是为了开发目的,你不需要让容器保持活动状态,除非它正在运行一个进程。nginx…)

Along with having something along the lines of : ENTRYPOINT ["tail", "-f", "/dev/null"] in your docker file, you should also run the docker container with -td option. This is particularly useful when the container runs on a remote m/c. Think of it more like you have ssh'ed into a remote m/c having the image and started the container. In this case, when you exit the ssh session, the container will get killed unless it's started with -td option. Sample command for running your image would be: docker run -td <any other additional options> <image name>

这适用于docker 20.10.2版本

你可以像兄弟@Sa'ad提到的那样,不带任何参数地运行plain cat,简单地让容器工作(实际上什么都不做,只是等待用户输入)(Jenkins的Docker插件也做同样的事情)

我刚刚遇到了同样的问题,我发现如果你运行带有-t和-d标志的容器,它会继续运行。

docker run -td <image>

下面是标志的作用(根据docker run——help):

-d, --detach=false         Run container in background and print container ID
-t, --tty=false            Allocate a pseudo-TTY

最重要的是-t标志。-d只是让你在后台运行容器。