Docker容器将在“docker run -d”之后自动停止。 [英] Docker container will automatically stop after "docker run -d"
问题描述
docker run -d
将从图像启动一个容器,容器将在后台运行。这是它的样子,我们可以看到我们已经有了容器ID。 root @ docker:/ home / root#docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d
但是,如果我运行 docker ps
,没有任何回报。
所以我尝试了 ps -a
,我可以看到已经退出的容器:
root @ docker :/ home / root#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
605e3928cddd centos:最新的/ bin / bash31分钟前已退出(0)31分钟前kickass_swartz
我做错了什么?如何解决这个问题?
centos dockerfile 具有默认命令 bash
。
这意味着,当在后台运行(-d)时,shell会立即退出。
如本文:
而不是使用
docker运行-i -t image your-command
,使用建议使用d
,因为只需一个命令即可运行容器,而不需要通过点击 Ctrl + P 来分离容器的终端。 + Q 。
但是,
-d
选项有问题。 您的容器立即停止,除非命令不在前台运行。
Docker要求您的命令在前台继续运行。否则,它会认为您的应用程序停止并关闭该容器。
问题是某些应用程序不会在前台运行。在这种情况下,您可以将
tail -f / dev / null
添加到您的命令。
通过这样做,即使您的主命令在后台运行,您的容器也不会停止,因为tail在前台继续运行。
所以这将工作:
docker run -d centos tail -f / dev / null
一个 docker ps
将显示中心容器仍在运行。
从那里,您可以附加到它或与其分离(或 docker exec
某些命令)。
According to tutorial I read so far, use "docker run -d
" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.
root@docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d
But if I ran "docker ps
", nothing was returned.
So I tried "docker ps -a
", I can see container already exited:
root@docker:/home/root# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
605e3928cddd centos:latest "/bin/bash" 31 minutes ago Exited (0) 31 minutes ago kickass_swartz
Anything I did wrong? How can I troubleshoot this issue?
The centos dockerfile has a default command bash
.
That means, when run in background (-d), the shell exits immediately.
As mentioned in this article:
Instead of running with
docker run -i -t image your-command
, using-d
is recommended because you can run your container with just one command and you don’t need to detach terminal of container by hitting Ctrl + P + Q.However, there is a problem with
-d
option. Your container immediately stops unless the commands are not running on foreground.
Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.The problem is that some application does not run in the foreground. How can we make it easier?
In this situation, you can add
tail -f /dev/null
to your command.
By doing this, even if your main command runs in the background, your container doesn’t stop because tail is keep running in the foreground.
So this would work:
docker run -d centos tail -f /dev/null
A docker ps
would show the centos container still running.
From there, you can attach to it or detach from it (or docker exec
some commands).
这篇关于Docker容器将在“docker run -d”之后自动停止。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!