1. 程式人生 > 實用技巧 >生產環境 Nginx 線上平滑升級

生產環境 Nginx 線上平滑升級

背景

生產環境 Nginx 需要增加支援 TCP 反向代理功能,需要再新增--with-stream引數重新編譯後,線上升級 Nginx。

線上升級

# 檢視當前版本(注意為大寫 V)
$ cd /usr/local/nginx/sbin
$ nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module

# 安裝編譯依賴
$ yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel

# 下載、解壓、並編譯(僅編譯不安裝)
$ wget http://nginx.org/download/nginx-1.16.1.tar.gz
$ tar -zxvf nginx-1.16.1.tar.gz
$ cd nginx-1.16.1
# 增加 --with-stream 編譯
# --pid-path 根據各自情況新增,由於 nginx 執行升級命令時,預設是從 nginx/logs 目錄下找 nginx.pid
$ ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-stream --pid-path=/usr/local/nginx/nginx.pid
# -j 指定CPU核心數量,加快編譯速度
$ make -j 4

# 備份舊版本,複製新版本
$ mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old
$ cp nginx-1.16.1/objs/nginx /usr/local/nginx/sbin/
$ chown nginx:nginx /usr/local/nginx/sbin/nginx

# 升級前檢視程序號,確認程序號與 nginx.pid 一致
$ ps -ef | grep nginx
root     11871     1  0 3月24 ?       00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx    13772 11871  0 11月10 ?      00:00:02 nginx: worker process
nginx    13773 11871  0 11月10 ?      00:00:03 nginx: worker process
nginx    13774 11871  0 11月10 ?      00:00:04 nginx: worker process
nginx    13775 11871  0 11月10 ?      00:00:04 nginx: worker process
$ cat /usr/local/nginx/nginx.pid
11871
 
# 在 nginx1.16.1 目錄下,執行 make upgrade 命令自動升級
$ cd nginx-1.16.1
$ make upgrade
# 使用新版本檢測配置檔案是否正確
/usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
# 傳送平滑遷移訊號給舊的 nginx 程序
kill -USR2 `cat /usr/local/nginx/nginx.pid`
sleep 1
# 檢測舊的 nginx.pid 程序是否變為 nginx.pid.oldbin
test -f /usr/local/nginx/nginx.pid.oldbin
# 結束舊版本的程序,完成升級
kill -QUIT `cat /usr/local/nginx/nginx.pid.oldbin` 
 
# 驗證是否升級成功,檢視 nginx 程序號是否變化(11871-->31845)
$ ps -ef | grep nginx
root     31845     1  0 16:58 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx    31847 31845  0 16:58 ?        00:00:00 nginx: worker process
nginx    31848 31845  0 16:58 ?        00:00:00 nginx: worker process
nginx    31849 31845  0 16:58 ?        00:00:00 nginx: worker process
nginx    31850 31845  0 16:58 ?        00:00:00 nginx: worker process
$ cat /usr/local/nginx/nginx.pid
31845

# 檢視升級後的版本(注意為大寫 V)
$ /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-stream --pid-path=/usr/local/nginx/nginx.pid

微信公眾號:daodaotest