nginx使用热部署添加新模块

1,130 阅读4分钟

简介

当初次编译安装nginx时,http_ssl_module 模块默认是不编译进nginx的二进制文件当中,如果需要添加 ssl 证书。也就是使用 https协议。那么则需要添加 http_ssl_module 模块。假设你的nginx安装包目录在/home/johnson/nginx-1.17.5,下面会用到

小知识点:使用/home/johnson/nginx-1.17.5/configure --help 命令,可以看到很多 --with--without 开头的模块选项。

  • --with:默认是不编译进nginx的二进制文件当中
  • --without:默认编译进nginx的二进制文件当中
/home/johnson/nginx-1.17.5/configure --help
...
  --with-http_ssl_module             enable ngx_http_ssl_module
...
  --without-http_gzip_module         disable ngx_http_gzip_module
...

可以看到http_ssl_module 模块默认是不编译进nginx的二进制文件当中。

编译添加新模块

当需要添加http_ssl_module模块时,命令如下:

/home/johnson/nginx-1.17.5/configure --with-http_ssl_module

执行完该命令后,可以在/home/johnson/nginx-1.17.5/objs/ngx_modules.c文件中看到哪些模块要安装到nginx中。如下:

ngx_module_t *ngx_modules[] = {
    &ngx_core_module,
...
    &ngx_http_ssl_module,
...

可以看到http_ssl_module模块要安装到nginx当中,然后使用make命令,把http_ssl_module编译进nginx的二进制文件当中

cd /home/johnson/nginx-1.17.5
make

执行完上述命令后,/home/johnson/nginx-1.17.5/objs/nginx该文件就是编译后的nginx二进制文件,然后咱们就需要进行热部署升级了。

热部署

假设你的nginx安装目录在/usr/local/nginx当中。 1.备份正在使用的nginx二进制文件

cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old

2.使用最新的nginx二进制文件替换掉正在使用的nginx二进制文件

cp -r /home/johnson/nginx-1.17.5/objs/nginx /usr/local/nginx/sbin/ -f

3.查看正在运行nginx的master进程

ps -ef | grep nginx
root      6503     1  0 Jun23 ?        00:00:00 nginx: master process nginx
ubuntu   26317 19063  0 07:39 pts/0    00:00:00 grep --color=auto nginx
nobody   31869  6503  0 Jun27 ?        00:00:00 nginx: worker process

可以看到,当前nginx的master进程号为 6503。

4.告知正在运行的nginx的master进程,需要进行nginx升级

kill -USR2 6503
ps -ef | grep nginx
root      6503     1  0 Jun23 ?        00:00:00 nginx: master process nginx
root      7128  6503  0 08:05 ?        00:00:00 nginx: master process nginx
nobody    7129  7128  0 08:05 ?        00:00:00 nginx: worker process
root      7140 30619  0 08:05 pts/0    00:00:00 grep --color=auto nginx
nobody   31869  6503  0 Jun27 ?        00:00:00 nginx: worker process

可以看到,执行完命令后会启动新的nginx的master进程,新的master进程是由旧的master进程启动的。如果没有启动,那么可以使用nginx -t查看配置文件是否正确,如果没有问题,那么一般是能够启动新的master进程。

5.告知旧的nginx master进程,请优雅的关闭所有旧的worker进程

kill -WINCH 6503
root@VM-0-13-ubuntu:/usr/local/nginx# ps -ef | grep nginx
root      6503     1  0 Jun23 ?        00:00:00 nginx: master process nginx
root      7128  6503  0 08:05 ?        00:00:00 nginx: master process nginx
nobody    7129  7128  0 08:05 ?        00:00:00 nginx: worker process
root      9431 30619  0 08:17 pts/0    00:00:00 grep --color=auto nginx

可以看到,旧的worker进程都已经关闭掉。如果发生了错误,则可以使用nginx -s reload命令回退到旧版本当中。
如果发现一切都正常,没有问题,那么你可以关闭掉旧的master进程。kill -9 6503,此时新的master进程的父进程(旧的master进程)被关闭后,那么会把他的父进程改成系统进程,系统进程的进程号为 1。
此时就完美添加了新模块和实现热部署了!!!

总结

因为初次编译nginx,可能没想到要用到其他模块,或许也可能删除某些模块。此时往往就需要使用到nginx的热部署。

参考文章:极客时间Nginx核心知识100讲: 第10讲

个人博客网址: colablog.cn/

如果我的文章帮助到您,可以关注我的微信公众号,第一时间分享文章给您

微信公众号