那么有什么技巧呢? Nginx 面向客户端。通常请求被转发到 80 端口的 gunicorn A。
您不能就地运行代码更新,因为可能出现问题。所以你做了一个新的代码检查并在某个端口 5678 上启动一个单独的 gunicorn B。
在开发/测试数据库上测试新代码后,您:
- 调整 gunicorn B 指向数据库,但不发送任何请求。
- 停止 gunicorn A。Nginx 现在,非常短暂地响应一个错误。
- 将 nginx 设置为指向 gunicorn B,仍然在端口 5678。
- 重启 nginx。
这样对吗?您是否只是编写一个脚本来更快地运行这四个操作并最大限度地减少服务器响应错误的持续时间(在步骤 2 和 4 之间)?
请您参考如下方法:
Nginx 支持 configuration reloading .使用此功能,更新您的应用程序可以像这样工作:
- 启动一个新实例 Gunicorn B。
- 调整 nginx 配置以将流量转发到 Gunicorn B。
- 使用
nginx -s reload重新加载 nginx 配置。在此之后,Gunicorn B 将服务于新请求,而 Gunicorn A 仍将完成对旧请求的服务。 - 等待旧的 nginx 工作进程退出(这意味着在重新加载之前发起的所有请求现在都已完成),然后停止 Gunicorn A。
假设您的应用程序在两个并发实例下正常工作,这将为您提供零停机更新。
nginx 文档的相关摘录:
Once the master process receives the signal to reload configuration, it checks the syntax validity of the new configuration file and tries to apply the configuration provided in it. If this is a success, the master process starts new worker processes and sends messages to old worker processes, requesting them to shut down. Otherwise, the master process rolls back the changes and continues to work with the old configuration. Old worker processes, receiving a command to shut down, stop accepting new connections and continue to service current requests until all such requests are serviced. After that, the old worker processes exit.
