模擬nginx熱部署

熱部署,就是在應用正在運行的時候升級軟件,卻不須要從新啓動應用。

首先在本地模擬一個線上須要升級 Nginx 的環境,假設舊版本爲 nginx-1.0.15,須要升級到 nginx-1.16.0。nginx

配置舊版本

# 下載 nginx-1.0.15
wget http://nginx.org/download/nginx-1.0.15.tar.gz

# 解壓壓縮包
tar -zxf nginx-1.0.15.tar.gz

# 進入解壓後的目錄
cd nginx-1.0.15

#  配置 nginx
./configure --prefix=/home/nginx

# 編譯安裝
make && make install

# 運行 nginx
sudo /home/nginx/sbin/nginx

此時訪問服務器地址應該能夠看到 nginx 的歡迎頁面了。服務器

得到新版本二進制

# 下載 nginx-1.16.0
wget http://nginx.org/download/nginx-1.16.0.tar.gz

# 解壓壓縮包
tar -zxf nginx-1.16.0

# 進入解壓後的目錄
cd nginx-1.16.0/

# 配置 nginx
./configure --prefix=/home/nginx

# 只編譯不須要安裝
make

在編譯後的 objs 目錄中,能夠看到二進制文件 nginx。code

熱部署

通過以上步驟,咱們實現了一個正在運行的舊版本 nginx 和編譯完成的新版本 nginx 二進制執行文件。進程

熱部署的流程是:部署

  1. 備份舊的 nginx 可執行文件
  2. 新的 nginx 可執行文件直接替換舊的(此時舊的 nginx 進程還在運行)
  3. 向 nginx master 進程發送熱部署信號,新的 nginx 進程啓動,舊的 worker 再也不就收請求。
  4. 關閉舊的 worker 進程,完成熱部署。
# 備份
cp /home/nginx/sbin/nginx /home/nginx/sbin/nginx.old

# 替換 
cp -f objs/nginx /home/nginx/sbin/nginx

# 查看 master pid
ps -ef | grep nginx 
root     23712     1  0 21:21 ?        00:00:00 nginx: master process /home/nginx/sbin/nginx
nobody   23715 23712  0 21:21 ?        00:00:00 nginx: worker process

# 發送熱部署信號,這裏 master pid 替換爲本身查詢到的
kill -USR2 23712

# 查看當前 nginx 進程狀況,27522 就是新的 master 進程
ps -ef | grep nginx 
root     23712     1  0 21:21 ?        00:00:00 nginx: master process /home/nginx/sbin/nginx
nobody   23715 23712  0 21:21 ?        00:00:00 nginx: worker process
root     27522 23712  0 21:41 ?        00:00:00 nginx: master process /home/nginx/sbin/nginx
nobody   27524 27522  0 21:41 ?        00:00:00 nginx: worker process

# 關閉舊的 worker
kill -WINCH 23712

# 再次查看進程,能夠發現舊的worker進程關閉了
ps -ef | grep nginx 
root     23712     1  0 21:21 ?        00:00:00 nginx: master process /home/nginx/sbin/nginx
root     27522 23712  0 21:41 ?        00:00:00 nginx: master process /home/nginx/sbin/nginx
nobody   27524 27522  0 21:41 ?        00:00:00 nginx: worker process

保留舊的 master 進程是爲了在新的版本存在問題時,能夠快速回退到原版本。若是發現問題要緊急回滾呢?get

cp -f nginx.old nginx
# 拉起舊版本的worker進程(-HUP 至關於 -s reload)
kill -HUP old_master_pid
# 讓新版本的 worker 再也不接受請求
kill -USR2 new_master_pid
# 關閉新版本的 woker 進程
kill -WINCH new_master_pid

若是確認無誤要退出老版本的 nginx,能夠執行命令:編譯

kill -QUIT old_master_pid
相關文章
相關標籤/搜索