daemon off
的实例分析daemon off
在 Docker 容器中运行 Nginx 时,使用 daemon off
是常见的最佳实践,主要原因包括:
docker run --name mynginx -p 80:80 nginx nginx -g "daemon off;"
FROM nginx:latest
# 其他配置...
CMD ["nginx", "-g", "daemon off;"]
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
CMD ["nginx", "-g", "daemon off;"]
在 nginx.conf
中也可以添加 daemon off;
指令。
docker run -d --name dev-nginx -p 8080:80 \
-v ./html:/usr/share/nginx/html \
nginx:alpine nginx -g "daemon off;"
FROM nginx:1.21.6
# 复制自定义配置
COPY nginx.conf /etc/nginx/nginx.conf
COPY sites-enabled/ /etc/nginx/sites-enabled/
COPY certs/ /etc/nginx/certs/
# 设置前台运行
CMD ["nginx", "-g", "daemon off;"]
如果需要同时运行多个进程,可以使用 Supervisor:
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y nginx supervisor
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY nginx.conf /etc/nginx/nginx.conf
# Nginx 配置中仍然需要 daemon off
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
CMD ["/usr/bin/supervisord"]
容器立即退出
daemon off
nginx -t
日志看不到输出
-it
参数进行交互式运行性能考虑
daemon off
运行 Nginxnginx -t
在构建时验证配置通过这种方式运行 Nginx,可以确保容器行为符合预期,并且与 Docker 的生态系统更好地集成。