本文探讨平滑升级nginx服务。
1 环境准备
1.1 安装环境准备
请参考 Nginx安装
1.2 下载新版本源码
http://nginx.org/en/download.html
升级至 nginx-1.17.9 版。
2 操作步骤
2.1 备份
任何线上操作,“备份”是第一且最重要的操作。
cd /usr/local
cp -r nginx nginx.bak
2.1 解压、编译、安装
将源码上传至/usr/local/src/目录。
解压:
cd /usr/local/src
tar -xvf nginx-1.17.9.tar.gz
编译:
cd nginx-1.17.9
./configure --with-http_ssl_module \
--with-pcre=/usr/local/src/pcre-8.44 \
--with-zlib=/usr/local/src/zlib-1.2.11 \
--with-openssl=/usr/local/src/openssl-1.1.1d
安装:
make
make install
执行 make install 后,新的nginx执行文件、默认配置文件(conf/*.default)等会被复制到安装目录。如果新版本nginx的安装目录与老版本nginx相同,在 nginx/sbin 目录下会保留旧版本的nginx可执行文件:
cd /usr/local/nginx/sbin
ls
nginx nginx.old
此时,新版本nginx安装文件已经准备好了,现在需要平滑升级正在运行的nginx。
2.2 平滑升级
- 查看旧版本nginx服务的master进程pid
cd /usr/local/nginx
cat logs/nginx.pid
得到正在运行的nginx服务master进程的pid [old_master_pid]:
78948
- 通知正在运行的旧版本nginx准备升级,并运行新版本nginx可执行文件。
kill -s USR2 [old_master_pid]
kill -s USR2 78948
执行此命令后,旧master会重命名nginx.pid为nginx.pid.oldbin,接着启动新的master、worker进程。此时新、旧worker同时处理请求。
查看logs目录下的文件
ls logs
得到:
nginx.pid nginx.pid.oldbin
查询nginx进程:
ps -ef |grep nginx
得到:
nobody 23033 78948 0 3月20 ? 00:01:40 nginx: worker process
nobody 23034 78948 0 3月20 ? 00:01:42 nginx: worker process
nobody 23035 78948 0 3月20 ? 00:01:50 nginx: worker process
nobody 23036 78948 0 3月20 ? 00:01:43 nginx: worker process
nobody 23037 78948 0 3月20 ? 00:01:38 nginx: worker process
nobody 23038 78948 0 3月20 ? 00:01:43 nginx: worker process
nobody 23039 78948 0 3月20 ? 00:01:43 nginx: worker process
nobody 23040 78948 0 3月20 ? 00:01:38 nginx: worker process
root 78948 1 0 2019 ? 00:00:00 nginx: master process ./nginx
root 129428 78948 0 14:58 ? 00:00:00 nginx: master process ./nginx
nobody 129429 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129430 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129431 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129432 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129433 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129434 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129435 129428 1 14:58 ? 00:00:00 nginx: worker process
nobody 129436 129428 0 14:58 ? 00:00:00 nginx: worker process
- 优雅停止旧版本nginx
kill -s QUIT [old_master_pid]
kill -s QUIT 78948
旧版本nginx完成处理所有请求后自动退出,仅保留新版本nginx进程。