docker运行nginx为什么要使用 daemon off
再返回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)! 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 中的entrypoint
和command
,以及 Dockerfile 中的ENTRYPOINT
和CMD
。
也就是说:
Docker 容器启动时,默认会把容器内部第一个进程,也就是
pid=1
的程序,作为docker容器是否正在运行的依据,如果 docker 容器pid=1的进程挂了,那么docker容器便会直接退出。Docker未执行自定义的CMD之前,nginx的pid是1,执行到CMD之后,nginx就在后台运行,bash或sh脚本的pid变成了1。
所以一旦执行完自定义CMD,nginx容器也就退出了。
https://hub.docker.com/_/nginx/