Docker启动Nginx容器有entrypoint或command时自动退出解决

8.9k 服务器 , 3评论

问题如标题所示,在升级优化 DNMP的时候,一直遇到这个问题没解决。

后来一遍遍谷歌后才在 reddit(地址在参考资料处) 上找到提示,

再返回Nginx的docker仓库仔细查看说明,其实是有说明的 /捂脸~

就是在CMD后面加上exec nginx -g 'daemon off;',如下:

command: /bin/bash -c "echo 'hello' && exec nginx -g 'daemon off;'"

Nginx的docker仓库原文说明如下:

If you add a custom CMD in the Dockerfile, be sure to include -g daemon off; in the CMD in order for nginx to stay in the foreground, so that Docker can track the process properly (otherwise your container will stop immediately after starting)!

— 这里的CMD适用 docker-compose.yml 中的entrypointcommand,以及 Dockerfile 中的ENTRYPOINTCMD

也就是说:

Docker 容器启动时,默认会把容器内部第一个进程,也就是pid=1的程序,作为docker容器是否正在运行的依据,如果 docker 容器pid=1的进程挂了,那么docker容器便会直接退出。

Docker未执行自定义的CMD之前,nginx的pid是1,执行到CMD之后,nginx就在后台运行,bash或sh脚本的pid变成了1。

所以一旦执行完自定义CMD,nginx容器也就退出了。

 

参考资料:

  1. [nginx:alpine] How to prevent exiting of the container after the entrypoint.sh script was executed?
  2. docker运行nginx为什么要使用 daemon off
  3. nginx daemon

3条评论

A
Aztekium.pl says: 回复

非常好的文章!

饿
饿 says: 回复

呃呃呃

牛牛 says: 回复

总算知道为什么debian容器不带-it 运行会无限自动重启了…

回复 Aztekium.pl 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

昵称 *