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

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

猜你喜欢

转载自blog.csdn.net/youcijibi/article/details/88781014