docker运行nginx为什么要使用 nginx -g 'daemon off;'

140 篇文章 1 订阅
83 篇文章 0 订阅

1.docker容器跑着为啥会挂掉?

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

2.docker run的时候把command最为容器内部命令,如果你使用nginx,那么nginx程序将后台运行,这个时候nginx并不是pid为1的程序,而是执行的bash,这个bash执行了nginx指令后就挂了,所以容器也就退出了,和你这个一样的道理,pm2 start 过后,bash 的pid为1,那么此时bash执行完以后会退出,所以容器也就退出了。

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)!

 

 

Running nginx in debug mode

Images since version 1.9.8 come with nginx-debug binary that produces verbose output when using higher log levels. It can be used with simple CMD substitution:

 

$ docker run --name my-nginx -v /host/path/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx nginx-debug -g 'daemon off;'

Similar configuration in docker-compose.yml may look like this:

 

web:

  image: nginx

  volumes:

    - ./nginx.conf:/etc/nginx/nginx.conf:ro

  command: [nginx-debug, '-g', 'daemon off;']

  

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容器也就退出了。

 

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值