nginx -g "daemon off;" 你学废了吗?

去年的时候写了一篇原创《前后端分离,如何在前端项目中动态插入后端API基地址?(in docker)》, 我自认为这篇生产实践是对大前端、 容器化、CI/CD的得意之作。

对于前后端分离的web项目,在容器启动的瞬间,通过脚本替换待部署环境的特定变量,形成了一个镜像,多环境部署的效果。

Dockerfile CMD指示容器运行过程:

  • 用真实值替换前端chunk files中插入的API_BASE_URL字符
  • 使用nginx承载替换后的chunk files
# FILE: Dockerfile
...
EXPOSE 80
COPY --from=builder /react-frontend/replace_api_url.sh /
CMD ["sh", "replace_api_url.sh"]

下面是replace_api_url.sh的内容

#!/usr/bin/env sh
find '/usr/share/nginx/html' -name '*.js' -exec sed -i -e 's,API_BASE_URL,'"$API_BASE_URL"',g' {} \;
nginx -g "daemon off;"

为什么要加 nginx -g "daemon off;"

这句话是什么意思?

在常规的虚机上,nginx默认是以守护进程来运行的(daemon on),在后台默默提供服务,同时部署多个ngxin服务也不会相互干扰。

nginx -g directives: set global directives out of configuration file.

在容器环境,one container == one process,容器要能持续运行,必须有且仅有一个前台进程,所以对nginx进程容器化,需要将nginx转为前后进程( daemon off)。

我们能顺利执行docker run nginx,启动容器并不退出,是因为nginx的官方镜像Dockerfile 已经指定 nginx -g "daemon off;"

再回到上文,为什么此处脚本中要加"nginx -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在执行的shell脚本["sh", "replace_api_url.sh"],实际上是启动shell进程来执行,脚本执行完,进程就会退出(此时nginx还是一摊死的物理文件),所以我们要在脚本内再添加nginx -g "daemon off;" 将整个shell进程转为前台能持续运行的进程。

Last

  • 容器= 进程, 有且仅有一个前台能持续运行的进程
  • nginx 默认是后台守护进程的形式运行, nginx -g "daemon off;" 以前台形式持续运行。

2022/06/14 ---

有个误区,我一直以为一个容器只能有一个进程, 其实是推荐作法。
在某些时候,两个program结合的很紧密的时候,也可以做成单容器内多进程

** 无论如何,保持一个前台进程 **
https://docs.docker.com/config/containers/multi-service_container/

posted @ 2021-12-31 17:22  博客猿马甲哥  阅读(21816)  评论(2编辑  收藏  举报