一、nginx基本概述
1.1nginx基本介绍
Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、简单的配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。
Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。
Nginx 是高性能的 HTTP 和反向代理的web服务器,处理高并发能力是十分强大的,能经受高负 载的考验,有报告表明能支持高达 50,000 个并发连接数。
Nginx支持热部署,启动简单,可以做到7*24不间断运行。几个月都不需要重新启动。
总结来说: Nginx是免费的、开源的、高性能的HTTP和反向代理服务器、邮件代理服务器、以及TCP/UDP代理服务器
nginx可以解决c10k问题
**现在已经可以解决c1000k问题,也就是百万级别 **
1.2nginx的功能介绍
- 静态的web服务器html,图片,js,css,txt等静态资源;
- http/https的反向代理
- 结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求;
- tcp/udp协议的请求转发(反向代理);
- imap4/pop3协议的反向代理;
1.3基础特性
- 模块化设计,比较好的扩展性,可以在github上获取想要的第三方库,自己编译安装;
- 高可靠性;
- 支持热部署:在不停机情况下更新配置文件,升级版本,更换日志文件;
- 低内存消耗:据资料显示10000个keep-alive连接模式下的非活动连接,只需要2.5M;
1.4web服务相关功能
- 虚拟主机(server)
- 支持 keep-alive 和管道连接(利用一个连接做多次请求)
- 访问日志(支持基于日志缓冲提高其性能)
- url rewirte 路径别名
- 基于IP及用户的访问控制
- 支持速率限制及并发数限制
- 重新配置和在线升级而无须中断客户的工作进程
二、nginx架构和进程
2.1nginx架构
Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处理网络请求与响应。
2.2nginx的进程结构
master进程主要用来管理worker进程,具体包括如下4个主要功能:
- 接收来自外界的信号。
- 向各worker进程发送信号。
- 监控worker进程的运行状态。
- 当worker进程退出后(异常情况下),会自动重新启动新的worker进程。
worker进程主要用来处理基本的网络事件:
- 多个worker进程之间是对等且相互独立的,他们同等竞争来自客户端的请求。
- 一个请求,只可能在一个worker进程中处理,一个worker进程,不可能处理其它进程的请求。
- worker进程的个数是可以设置的,一般我们会设置与机器cpu核数一致。同时,nginx为了更好的利用多核特性,具有cpu绑定选项,我们可以将某一个进程绑定在某一个核上,这样就不会因为进程的切换带来cache的失效。
主进程master process 的功能:
- 对外接口:接收外部的操作(信号)
- 对内转发:根据外部的操作的不同,通过信号管理 Worker
- 监控:监控 worker 进程的运行状态,worker 进程异常终止后,自动重启 worker 进程
- 读取Nginx 配置文件并验证其有效性和正确性 建立、绑定和关闭socket连接
- 按照配置生成、管理和结束工作进程 接受外界指令,比如重启、升级及退出服务器等指令
- 不中断服务,实现平滑升级,重启服务并应用新的配置
- 开启日志文件,获取文件描述符
- 不中断服务,实现平滑升级,升级失败进行回滚处理
- 编译和处理perl脚本
工作进程worker process 的功能:
- 所有 Worker 进程都是平等的
- 实际处理:网络请求,由 Worker 进程处理
- Worker进程数量:一般设置为核心数,充分利用CPU资源,同时避免进程数量过多,导致进程竞争CPU资源, 增加上下文切换的损耗
- 接受处理客户的请求
- 将请求依次送入各个功能模块进行处理
- I/O调用,获取响应数据
- 与后端服务器通信,接收后端服务器的处理结果
- 缓存数据,访问缓存索引,查询和调用缓存数据
- 发送请求结果,响应客户的请求
- 接收主程序指令,比如重启、升级和退出等
2.3Nginx启动和HTTP建立连接
- nginx 启动时,master进程首先先加载配置文件;
- master进程,初始化监听socker;
- master进程,创建出多个worker进程;
- worker进程,竞争新的连接,获取者可以通过三次握手,建立socker连接,并请求处理
2.4http处理过程
nginx是一种高性能的web服务器,可以处理大量的并发HTTP请求。nginx在处理HTTP请求时采用了高效的事件驱动模型,使用异步IO等技术实现了高性能,低延迟的请求处理;
在处理http请求时,nginx会通过一下步骤进行处理:
- 解读请求:当客户端发送HTTP请求时,nginx会使用socker接口读取请求,包括请求头和请求体。
- 解析请求:nginx会对请求进行解析,包括解析请求方法、请求路径、查询参数等信息。nginx还会对请求头进行解析,包括解析Host、User-Agent、Content-Type等字段,这些信息可以在后续处理中使用;
- 处理请求:根据解析得到的请求信息,你nginx会今昔请求处理。比如如果请求路径对应的是一个静态文件,nginx会直接返回文件内容;如果请求路径对应的十一动态页面,nginx会将请求转发给后端服务器。
- 处理请求体:如果请求包含请求体,nginx会将请求体读取到内存中,以供后续处理使用;
- 处理响应:当请求处理完成后,nginx会根据结果生成响应,并发给客户端。nginx会将响应头和响应头一起发送给客户端,响应头中包含响应状态码、响应头字段信息;
- 关闭连接:当请求处理完成后,nginx会关闭连接,释放资源,等待下一个请求;
三、nginx安装
3.1nginx版本和安装方式
nginx分为商业版本和社区版本,我们一般会使用社区版本;
nginx版本:
- Mainline version 主要开发版本,一般为奇数版本版本号,如1.23
- srable version 当前最新稳定版本,一般为偶数版本,如1.24;
- Lergacy version 旧的稳定版本,一般为旧的偶数版本,如1.22;
nginx安装可以使用yum或者源码安装,推荐使用源码编译安装:
- yum/apt安装的版本比较旧
- 编译安装可以更方便自定义相关路径,使用源码编译可以自定功能,同时可以获取GitHub上的模块增加,以及实现nginx的升级和后退;
- docker容器直接运行
3.2基于ubuntu包安装nginx
3.2.1使用Ubuntu配置的阿里源安装nginx
apt list 列出库中最新安装包
root@ubuntu202:~# apt list nginx
Listing... Done
nginx/focal-security,focal-updates 1.18.0-0ubuntu1.4 all
N: There is 1 additional version. Please use the '-a' switch to see
apt list -a 列出所有可以选的包
root@ubuntu202:~# apt list -a nginx
Listing... Done
nginx/focal-security,focal-updates 1.18.0-0ubuntu1.4 all
nginx/focal 1.17.10-0ubuntu1 all
如果直接使用阿里源中安装nginx,直接apt -y install nginx
root@ubuntu202:~# apt list nginx
# 安装好了后使用nginx -v查看版本
root@ubuntu202:~# nginx -v
nginx version: nginx/1.18.0 (Ubuntu)
# 卸载nginx
root@ubuntu202:~# apt list nginx
直接使用阿里源安装nginx十分简单,因为我们主要使用的源码安装,这里就不多说了;
3.2.2配置官方的nginx源安装
nginx官方网址:https://nginx.org/en/linux_packages.html
选择ubuntu
官方安装过程
nstall the prerequisites:
安装需要的包
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring
Import an official nginx signing key so apt could verify the packages authenticity. Fetch the key:
导入官方 nginx 签名密钥,以便 apt 可以验证软件包 真实性。 获取密钥:
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
| sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
Verify that the downloaded file contains the proper key:
验证下载的文件是否包含正确的密钥:
gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg
输出应包含完整的指纹,如下所示:573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
pub rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
uid nginx signing key <signing-key@nginx.com>
If the fingerprint is different, remove the file.
如果指纹不同,请删除该文件。
To set up the apt repository for stable nginx packages, run the following command:
要为稳定的 nginx 软件包设置 apt 存储库, 运行以下命令:
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
If you would like to use mainline nginx packages, run the following command instead:
如果您想使用主线 nginx 包, 请改为运行以下命令:
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/mainline/ubuntu `lsb_release -cs` nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
Set up repository pinning to prefer our packages over distribution-provided ones:
设置存储库固定以首选我们的包 发行版提供的:
echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
| sudo tee /etc/apt/preferences.d/99nginx
To install nginx, run the following commands:
要安装 nginx,请运行以下命令:
sudo apt update
sudo apt install nginx
3.38基于Redhat的centos安装nginx
3.3.1centos配置官方的nginx源,安装nginx
Install the prerequisites:
安装先决条件:
sudo yum install yum-utils
To set up the yum repository, create the file named with the following contents: /etc/yum.repos.d/nginx.repo
要设置 yum 存储库,请创建以下内容:/etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
By default, the repository for stable nginx packages is used. If you would like to use mainline nginx packages, run the following command:
默认情况下,使用稳定 nginx 软件包的存储库。 如果您想使用主线 nginx 包, 运行以下命令:
sudo yum-config-manager --enable nginx-mainline
To install nginx, run the following command:
要安装 nginx,请运行以下命令:
sudo yum install nginx
When prompted to accept the GPG key, verify that the fingerprint matches , and if so, accept it. 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62
当系统提示接受 GPG 密钥时,请验证指纹是否匹配 , 如果是这样,请接受它。573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62
查看所有nginx版本
[root@centos71 ~]# yum list nginx --showduplicates
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
Available Packages
nginx.x86_64 1:1.8.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.8.1-1.el7.ngx nginx-stable
nginx.x86_64 1:1.10.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.10.1-1.el7.ngx nginx-stable
nginx.x86_64 1:1.10.2-1.el7.ngx nginx-stable
nginx.x86_64 1:1.10.3-1.el7.ngx nginx-stable
nginx.x86_64 1:1.12.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.12.1-1.el7.ngx nginx-stable
nginx.x86_64 1:1.12.2-1.el7_4.ngx nginx-stable
nginx.x86_64 1:1.14.0-1.el7_4.ngx nginx-stable
nginx.x86_64 1:1.14.1-1.el7_4.ngx nginx-stable
nginx.x86_64 1:1.14.2-1.el7_4.ngx nginx-stable
nginx.x86_64 1:1.16.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.16.1-1.el7.ngx nginx-stable
nginx.x86_64 1:1.18.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.18.0-2.el7.ngx nginx-stable
nginx.x86_64 1:1.20.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.20.1-1.el7.ngx nginx-stable
nginx.x86_64 1:1.20.2-1.el7.ngx nginx-stable
nginx.x86_64 1:1.22.0-1.el7.ngx nginx-stable
nginx.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx.x86_64 1:1.24.0-1.el7.ngx nginx-stable
查看最新版本信息
[root@centos71 ~]# yum info nginx
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
Available Packages
Name : nginx
Arch : x86_64
Epoch : 1
Version : 1.24.0
Release : 1.el7.ngx
Size : 804 k
Repo : nginx-stable/7/x86_64
Summary : High performance web server
URL : https://nginx.org/
License : 2-clause BSD-like license
Description : nginx [engine x] is an HTTP and reverse proxy server, as well as
: a mail proxy server.
安装nginx
yum -y install nginx
查看安装包信息:
[root@centos71 ~]# rpm -q nginx
nginx-1.24.0-1.el7.ngx.x86_64
[root@centos71 ~]# rpm -qi nginx
Name : nginx
Epoch : 1
Version : 1.24.0
Release : 1.el7.ngx
Architecture: x86_64
Install Date: Wed 03 Apr 2024 06:00:23 PM CST
Group : System Environment/Daemons
Size : 2938462
License : 2-clause BSD-like license
Signature : RSA/SHA256, Wed 12 Apr 2023 01:47:07 AM CST, Key ID abf5bd827bd9bf62
Source RPM : nginx-1.24.0-1.el7.ngx.src.rpm
Build Date : Wed 12 Apr 2023 01:22:36 AM CST
Build Host : ip-10-1-17-154.eu-central-1.compute.internal
Relocations : (not relocatable)
Vendor : NGINX Packaging <nginx-packaging@f5.com>
URL : https://nginx.org/
Summary : High performance web server
Description :
nginx [engine x] is an HTTP and reverse proxy server, as well as
a mail proxy server.
#
查看nginx
[root@centos71 ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.24.0
/usr/share/doc/nginx-1.24.0/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx
# 带有自动日志切割功能
[root@centos71 ~]# cat /etc/logrotate.d//nginx
/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
3.3.2 nginx二进制命令使用
# nginx -h 查看命令帮助
[root@centos71 ~]# nginx -h
nginx version: nginx/1.24.0
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
[-e filename] [-c filename] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit #显示版本和编译参数
-t : test configuration and exit #测试配置文件是否异常
-T : test configuration, dump it and exit #测试并打印
-q : suppress non-error messages during configuration testing #静默模
# 式
-s signal : send signal to a master process: stop, quit, reopen, reload
#发送信号,reload信号会生成新的worker,但master不会重新生成
-p prefix : set prefix path (default: /etc/nginx/) #指定Nginx 目录
-e filename : set error log file (default: /var/log/nginx/error.log)
-c filename : set configuration file (default: /etc/nginx/nginx.conf)#配置
# 文件路径
-g directives : set global directives out of configuration file #设置全
# 局指令,注意和配置文件不要同时配置,否则冲突
验证nginx
[root@www ~]# nginx -t # 检查nginx配置文件
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -v # 查看nginx版本
nginx version: nginx/1.24.0
[root@www ~]# nginx -v
nginx version: nginx/1.24.0
[root@www ~]# nginx -V # 查看nginx详细安装过程
nginx version: nginx/1.24.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
nginx启动
nginx启动文件
[root@www ~]# cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"
[Install]
WantedBy=multi-user.target
nginx配置文件
[root@www ~]# rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
# 配置文件目录结构
[root@www ~]# tree /etc/nginx/
/etc/nginx/
├── conf.d
│ └── default.conf
├── default.d
├── fastcgi_params
├── mime.types
├── modules -> ../../usr/lib64/nginx/modules
├── nginx.conf
├── nginx.conf.rpmsave
├── scgi_params
└── uwsgi_params
3 directories, 7 files
# nginx的默认配置文件
[root@www ~]# grep -Ev '^$|^#' /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
启动nginx
# 启动nginx,并且加入开机自启动
[root@www ~]# systemctl enable --now nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
# 查看nginx状态
[root@www ~]# systemctl status nginx
● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 一 2024-04-01 23:45:43 CST; 57s ago
Docs: http://nginx.org/en/docs/
Process: 7546 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Main PID: 7547 (nginx)
CGroup: /system.slice/nginx.service
├─7547 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
├─7548 nginx: worker process
└─7549 nginx: worker process
4月 01 23:45:43 www.gw.com systemd[1]: Starting nginx - high performance web server...
4月 01 23:45:43 www.gw.com systemd[1]: Started nginx - high performance web server.
# 查看nginx进程
[root@www ~]# ps -ef |grep nginx
root 7547 1 0 23:45 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx 7548 7547 0 23:45 ? 00:00:00 nginx: worker process
nginx 7549 7547 0 23:45 ? 00:00:00 nginx: worker process
访问nginx
可以访问到这个页面就可以说明nginx安装成功了
3.4 nginx的编译安装
3.4.1编译安装nginx
官方源码包下载地址:https://nginx.org/en/download.html
nginx编译安装示例:
# 在cengto7上演示安装
# 安装编译需要的依赖
[root@www ~]# yum -y install gcc make pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
# 创建nginx用户
[root@www ~]# useradd -s /sbin/nologin nginx
# 切换到下载目录
[root@www src]# cd /usr/local/src/
# wget下载版本
[root@www src]# wget http://nginx.org/download/nginx-1.24.0.tar.gz
--2024-04-02 00:01:38-- http://nginx.org/download/nginx-1.22.0.tar.gz
正在解析主机 nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:5c0:2600::6, ...
正在连接 nginx.org (nginx.org)|52.58.199.22|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1112471 (1.1M) [application/octet-stream]
正在保存至: “nginx-1.24.0.tar.gz”
100%[======================================================================================================>] 1,112,471 808KB/s 用时 1.3s
2024-04-02 00:01:40 (808 KB/s) - 已保存 “nginx-1.22.0.tar.gz” [1112471/1112471])
# 解压nginx压缩包
[root@www src]# tar -xf nginx-1.22.0.tar.gz
# 到nginx包目录下
[root@www src]# cd nginx-1.22.0/
[root@www nginx-1.22.0]# ll
总用量 800
drwxr-xr-x 6 1001 1001 326 4月 2 00:03 auto
-rw-r--r-- 1 1001 1001 317070 5月 24 2022 CHANGES
-rw-r--r-- 1 1001 1001 484445 5月 24 2022 CHANGES.ru
drwxr-xr-x 2 1001 1001 168 4月 2 00:03 conf
-rwxr-xr-x 1 1001 1001 2590 5月 24 2022 configure
drwxr-xr-x 4 1001 1001 72 4月 2 00:03 contrib
drwxr-xr-x 2 1001 1001 40 4月 2 00:03 html
-rw-r--r-- 1 1001 1001 1397 5月 24 2022 LICENSE
drwxr-xr-x 2 1001 1001 21 4月 2 00:03 man
-rw-r--r-- 1 1001 1001 49 5月 24 2022 README
drwxr-xr-x 9 1001 1001 91 4月 2 00:03 src
# 有一个configure文件,编译
[root@www nginx-1.22.0]# ./configure --prefix=/app/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
[root@www nginx-1.22.0]# make && make install
# 生成目录
[root@www nginx]# ll
总用量 0
drwxr-xr-x 2 root root 333 4月 2 00:11 conf
drwxr-xr-x 2 root root 40 4月 2 00:11 html
drwxr-xr-x 2 root root 6 4月 2 00:11 logs
drwxr-xr-x 2 root root 19 4月 2 00:11 sbin
- conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他 的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和 fastcgi_params两个文件,配置文件一般都有一个样板配置文件,是以.default为后缀,使用时可将其复 制并将default后缀去掉即可。
- html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的 web文件是默认的错误页面提示页面。
- logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比 如/var/logs/nginx里面。
- sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。
3.4.2验证版本及参数
# 更加目录用户和用户组
[root@www nginx]# chown -R nginx.nginx /app/nginx
# 创建软连接
[root@www nginx]#ln -s /app/nginx/sbin/nginx /usr/local/sbin/nginx
# 查看nginx版本,以及编译安装的模块
[root@centos71 ~]# nginx -v
nginx version: nginx/1.22.0
[root@centos71 ~]# nginx -V
nginx version: nginx/1.22.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/app/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
3.4.3启动和关闭nginx以及页面测试
# 启动nginx
[root@centos71 ~]# nginx
[root@centos71 ~]# ps -ef |grep nginx
root 37434 1 0 14:30 ? 00:00:00 nginx: master process nginx
nginx 37435 37434 0 14:30 ? 00:00:00 nginx: worker process
root 37437 37345 0 14:31 pts/0 00:00:00 grep --color=auto nginx
# 关闭nginx
[root@centos71 ~]# ps -ef |grep nginx
root 37434 1 0 14:30 ? 00:00:00 nginx: master process nginx
nginx 37435 37434 0 14:30 ? 00:00:00 nginx: worker process
root 37437 37345 0 14:31 pts/0 00:00:00 grep --color=auto nginx
访问nginx
3.4.4创建nginx自启动文件
[root@centos71 ~]# vim /lib/systemd/system/nginx.server
# 写入以内容
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/app/nginx/logs/nginx.pid
ExecStartPre=/bin/rm -f /app/nginx/logs/nginx.pid
ExecStartPre=/app/nginx/sbin/nginx -t
ExecStart=/app/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
LimitNOFILE=100000
[Install]
WantedBy=multi-user.target
# 创建nginx存放pid文件
[root@centos71 ~]# mkdir /app/nginx/logs
# 修改nginx的配置文件
[root@centos71 ~]# vim /app/nginx/conf/nginx.conf
[root@centos71 ~]# cat /app/nginx/conf/nginx.conf |grep pid
pid /app/nginx/logs/nginx.pid;
3.4.5自启动文件
[root@centos71 ~]# systemctl daemon-reload
[root@centos71 ~]# systemctl start nginx
[root@centos71 ~]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2024-04-05 14:59:56 CST; 3min 1s ago
Process: 41166 ExecStart=/app/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
Process: 41163 ExecStartPre=/app/nginx/sbin/nginx -t (code=exited, status=0/SUCCESS)
Process: 41161 ExecStartPre=/bin/rm -f /app/nginx/logs/nginx.pid (code=exited, status=0/SUCCESS)
Main PID: 41168 (nginx)
CGroup: /system.slice/nginx.service
├─41168 nginx: master process /app/nginx/sbin/nginx
└─41169 nginx: worker process
Apr 05 14:59:56 centos71 systemd[1]: Starting The nginx HTTP and reverse proxy server...
Apr 05 14:59:56 centos71 nginx[41163]: nginx: the configuration file /app/nginx/conf/nginx.conf syntax is ok
Apr 05 14:59:56 centos71 nginx[41163]: nginx: configuration file /app/nginx/conf/nginx.conf test is successful
Apr 05 14:59:56 centos71 systemd[1]: Started The nginx HTTP and reverse proxy server.
四、nginx的模块介绍
4.1nginx的多种模块
- 核心模块:是 Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件 驱动机制 、进程管理等核心功能
- 标准HTTP模块:提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应 头设置等
- 可选HTTP模块:主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如: Flash 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等
- 邮件服务模块:主要用于支持 Nginx 的 邮件服务 ,包括对 POP3 协议、 IMAP 协议和 SMTP协议 的支持
- Stream服务模块: 实现反向代理功能,包括TCP协议代理
- 第三方模块:是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支 持等
4.2模块分类
核心模块:core module
标准模块:
HTTP 模块: ngx_http_*
HTTP Core modules #默认功能
HTTP Optional modules #需编译时指定
Mail 模块: ngx_mail_*
Stream 模块 ngx_stream_*
第三方模块
4.3模块图
五、nginx的信号和命令
5.1nginx命令
nginx命令支持想其发送信号,实现不同功能
nginx格式
nginx [-?hvVtTq] [-s signal] [-p prefix] [-e filename] [-c filename] [-g directives]
选项说明
# 帮助: -? -h
# 使用指定的配置文件: -c
# 指定配置指令:-g
# 指定运行目录:-p
# 测试配置文件是否有语法错误:-t -T
# 打印nginx的版本信息、编译信息等:-v -V
# 发送信号: -s 示例: nginx -s reloa
信号说明:
# 立刻停止服务:stop,相当于信号SIGTERM,SIGINT
# 优雅的停止服务:quit,相当于信号SIGQUIT
# 平滑重启,重新加载配置文件: reload,相当于信号SIGHUP
# 重新开始记录日志文件:reopen,相当于信号SIGUSR1,在切割日志时用途较大
# 平滑升级可执行程序:发送信号SIGUSR2,在升级版本时使用
# 优雅的停止工作进程:发送信号SIGWINCH,在升级版本时使用
查看nginx帮助:
[root@centos72 ~]# nginx -h
nginx version: nginx/1.24.0
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
[-e filename] [-c filename] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /etc/nginx/)
-e filename : set error log file (default: /var/log/nginx/error.log)
-c filename : set configuration file (default: /etc/nginx/nginx.conf)
-g directives : set global directives out of configuration file
5.2 reload流程
利用 reload 可以实现平滑修改配置并生效
- 向master进程发送HUP信号(reload命令)
- master进程校验配置语法是否正确
- master进程打开新的监听端口
- master进程用新配置启动新的worker子进程
- master进程向老worker子进程发送QUIT信号,老的worker对已建立连接继续处理,处理完才会优 雅退出.未关闭的worker旧进程不会处理新来的请求
- 老worker进程关闭监听句柄,处理完当前连接后结束进程
六、nginx的升级和回滚
6.1nginx平滑升级流程
平滑升级四个阶段
- 只有旧版nginx的master和worker进程
- 旧版和新版nginx的master和worker进程并存,由旧版nginx接收处理用户的新请求
- 旧版和新版nginx的master和worker进程并存,由新版nginx接收处理用户的新请求
- 只有新版nginx的master和worker进程
- 编译新版本,生成新版本的二进制文件
- 用新Nginx程序文件替换旧Nginx二进制文件(注意先备份旧版本的二进制文件)
- 向旧版本的master进程发送USR2信号启动新nginx进程
master进程修改pid文件名加上后缀.oldbin,成为nginx.pid.oldbin
将新生成的master进程的PID存放至新生成的pid文件nginx.pid
master进程用新Nginx二进制文件启动新master进程及worker子进程成为旧master的子进程
系统中将有新旧两个Nginx主进程和对应的worker子进程并存
当前新的请求仍然由旧Nginx的worker进程进行处理
- 向旧的Nginx服务进程发送WINCH信号,使旧的Nginx worker进程平滑停止,旧的Nginx worker
进程将不再接收新请求
当前新的请求由新Nginx的worker进程进行处理
旧的Nginx Master进程仍然存在
测试访问确认新版本是否正常工作
- 如果发现升级正常,向旧master进程发送QUIT信号,关闭旧master,并删除Nginx.pid.oldbin文
件,到此旧版本的Nginx彻底下线,新版本正式上线
- 如果发现升级有问题,可以回滚∶向旧master发送HUP,旧版本的worker开始接收新请求,向新
master发送QUIT
6.2平滑升级和回滚案例
# 制作一个文件,链接这下载,然后施行平滑升级
[root@www conf.d]# dd if=/dev/zero of=/data/download/test.txt bs=10M count=100
记录了100+0 的读入
记录了100+0 的写出
1048576000字节(1.0 GB)已复制,7.09517 秒,148 MB/秒
# 修改nginx配置文件,使nginx成为下载服务器
[root@www ~]# grep -Ev '#|^$' /apps/nginx/conf/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# 增加这一行
include conf.d/*.conf;
}
# 新建一个conf.d文件夹
[root@www ~]# mkdir /apps/nginx/conf/conf.d/
# 新建一个配置文件写入
[root@www ~]# vim /apps/nginx/conf/conf.d/download.conf
server {
listen 80;
server_name www.gw.com;
root /data/download;
location / {
autoindex on;
limit_rate 10k;
}
}
# 在另外一台服务器上配置本地域名解析
[root@localhost ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
10.1.1.135 www.gw.com
# 测试
[root@localhost ~]# curl www.gw.com
<html>
<head><title>Index of /</title></head>
<body>
<h1>Index of /</h1><hr><pre><a href="../">../</a>
<a href="test.txt">test.txt</a> 05-Apr-2024 12:56 1048576000
</pre><hr></body>
</html>
# 开始下载
[root@localhost ~]# wget www.gw.com/test.txt
--2024-04-05 21:10:16-- http://www.gw.com/test.txt
正在解析主机 www.gw.com (www.gw.com)... 10.1.1.135
正在连接 www.gw.com (www.gw.com)|10.1.1.135|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1048576000 (1000M) [text/plain]
正在保存至: “test.txt”
# 在10.1.1.134上查看链接
[root@www ~]# lsof -i :80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 14956 root 6u IPv4 33828 0t0 TCP *:http (LISTEN)
nginx 18453 nginx 3u IPv4 36940 0t0 TCP www.gw.com:http->10.1.1.130:54774 (ESTABLISHED)
nginx 18453 nginx 6u IPv4 33828 0t0 TCP *:http (LISTEN)
# 下载最新的nginx二进制包
[root@www ~]# wget http://nginx.org/download/nginx-1.24.0.tar.gz
# 解压nginx包
[root@www ~]# tar xvf nginx-1.24.0.tar.gz
# 查看当前使用的nginx版本和编译选项
[root@www ~]# nginx -V
nginx version: nginx/1.22.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
# 将原来二进制文件进行备份
[root@www ~]# cd /apps/nginx/sbin/
[root@www sbin]# cp nginx /opt/nginx
# 按照原有的编译过程进行编译新的包
[root@www nginx-1.24.0]# ./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
# 执行make不执行makeinstall
[root@www nginx-1.24.0]# make
# 查看新的版本
[root@www nginx-1.24.0]# objs/nginx -v
nginx version: nginx/1.24.0
# 将该二进制文件复制到/apps/nginx/sbin/nginx下
[root@www nginx-1.24.0]# cp -f objs/nginx /apps/nginx/sbin/
cp:是否覆盖"/apps/nginx/sbin/nginx"? y
# 检查新旧版本nginx配置文件是否兼容
[root@www nginx-1.24.0]# /apps/nginx/sbin/nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
#发送信号USR2 平滑升级可执行程序,将存储有旧版本主进程PID的文件重命名为nginx.pid.oldbin,并启动新的nginx
#此时两个master的进程都在运行,只是旧的master不在监听,由新的master监听80
#此时Nginx开启一个新的master进程,且这个新master进程会生成新的worker进程,即升级后的Nginx进
#程,此时老的进程不会自动退出,新的请求仍由旧进程处理。
[root@www nginx-1.24.0]# kill -USR2 `cat /apps/nginx/logs/nginx.pid`
#可以看到两个master,新的master是旧版master的子进程,并生成新版的worker进程
#注意:在Nginx-1.22.1版中如果看不到下面新版进程,需要重新使用service方式重新启动nginx服务再发送USR2信号
[root@www nginx-1.24.0]# ps auxf|grep nginx
root 18604 0.0 0.0 112824 988 pts/0 S+ 21:20 0:00 \_ grep --color=auto nginx
root 14956 0.0 0.1 46352 2084 ? Ss 18:22 0:00 nginx: master process /apps/nginx/sbin/nginx
nginx 18453 0.0 0.1 46836 2300 ? S 21:01 0:00 \_ nginx: worker process
root 18601 0.0 0.1 46232 3452 ? S 21:20 0:00 \_ nginx: master process /apps/nginx/sbin/nginx
nginx 18602 0.0 0.1 46720 1944 ? S 21:20 0:00 \_ nginx: worker process
[root@www nginx-1.24.0]# lsof -i :80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 14956 root 6u IPv4 33828 0t0 TCP *:http (LISTEN)
nginx 18453 nginx 3u IPv4 36940 0t0 TCP www.gw.com:http->10.1.1.130:54774 (ESTABLISHED)
nginx 18453 nginx 6u IPv4 33828 0t0 TCP *:http (LISTEN)
nginx 18601 root 6u IPv4 33828 0t0 TCP *:http (LISTEN)
nginx 18602 nginx 6u IPv4 33828 0t0 TCP *:http (LISTEN)
# 现在访问依旧是旧版本提供服务
guowang@ubuntu2204:~$ curl -I 10.1.1.135
HTTP/1.1 200 OK
Server: nginx/1.22.0
Date: Fri, 05 Apr 2024 13:23:28 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 05 Apr 2024 10:22:07 GMT
Connection: keep-alive
ETag: "660fd0cf-267"
Accept-Ranges: bytes
#先关闭旧nginx的worker进程,而不关闭旧nginx主进程方便回滚
#向原老的Nginx主进程发送WINCH信号,它会平滑关闭老的工作进程(主进程不退出),这时所有新请求都会由新版Nginx处理
# 新的版本会生成新的pid文件
[root@www logs]# ll /apps/nginx/logs/
总用量 16
-rw-r--r-- 1 root root 347 4月 5 21:23 access.log
-rw-r--r-- 1 root root 351 4月 5 21:20 error.log
-rw-r--r-- 1 root root 6 4月 5 21:20 nginx.pid
-rw-r--r-- 1 root root 6 4月 5 18:22 nginx.pid.oldbin
[root@www logs]# kill -WINCH `cat /apps/nginx/logs/nginx.pid.oldbin`
#如果旧版worker进程有用户的旧的请求,会一直等待处理完后才会关闭,即平滑关闭
[root@www logs]# ps -auxf|grep nginx
root 18636 0.0 0.0 112824 988 pts/0 S+ 21:28 0:00 \_ grep --color=auto nginx
root 14956 0.0 0.1 46352 2084 ? Ss 18:22 0:00 nginx: master process /apps/nginx/sbin/nginx
nginx 18453 0.0 0.1 46836 2300 ? S 21:01 0:00 \_ nginx: worker process is shutting down
root 18601 0.0 0.1 46232 3452 ? S 21:20 0:00 \_ nginx: master process /apps/nginx/sbin/nginx
nginx 18602 0.0 0.1 46720 1944 ? S 21:20 0:00 \_ nginx: worker process
# 在访问就由新的nginx版本提供服务
guowang@ubuntu2204:~$ curl -I 10.1.1.135
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 05 Apr 2024 13:28:45 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 05 Apr 2024 10:22:07 GMT
Connection: keep-alive
ETag: "660fd0cf-267"
Accept-Ranges: bytes
#经过一段时间测试,新版本服务没问题,最后发送QUIT信号,退出老的master,完成全部升级过程
[root@www logs]# kill -QUIT `cat /apps/nginx/logs/nginx.pid.oldbin`
# 现在查看版本已经是新版本了
[root@www logs]# nginx -v
nginx version: nginx/1.24.0
#如果有旧的连接,不会立即关闭旧版本的Master和对应的Worker进程,直到所有旧连接断开,才会关闭所的旧的进程
[root@www logs]# ps -auxf |grep nginx
root 18663 0.0 0.0 112824 984 pts/0 S+ 21:32 0:00 \_ grep --color=auto nginx
root 14956 0.0 0.1 46352 2084 ? Ss 18:22 0:00 nginx: master process /apps/nginx/sbin/nginx
nginx 18453 0.0 0.1 46836 2300 ? S 21:01 0:00 \_ nginx: worker process is shutting down
root 18601 0.0 0.1 46232 3452 ? S 21:20 0:00 \_ nginx: master process /apps/nginx/sbin/nginx
nginx 18602 0.0 0.1 46720 2188 ? S 21:20 0:00 \_ nginx: worker process
# 关闭旧的下载在看,发现以及没有旧的进程了
[root@www logs]# ps -auxf |grep nginx
root 18665 0.0 0.0 112824 988 pts/0 S+ 21:33 0:00 \_ grep --color=auto nginx
root 18601 0.0 0.1 46232 3452 ? S 21:20 0:00 nginx: master process /apps/nginx/sbin/nginx
nginx 18602 0.0 0.1 46720 2188 ? S 21:20 0:00 \_ nginx: worker process
#####################################回滚###########################################
#如果升级的新版本发现问题需要回滚,可以发送HUP信号,重新拉起旧版本的worker
[root@www logs]#kill -HUP `cat /apps/nginx/logs/nginx.pid.oldbin`
#最后关闭新版的master和worker,如果不执行上面的HUP信号,此步QUIT信号也可以重新拉起旧版本的
#worker进程
[root@centos8 nginx-1.20.1]#kill -QUIT `cat /apps/nginx/logs/nginx.pid`
#恢复旧版的文件
[root@rocky8 ~]#mv /opt/nginx /apps/nginx/sbin/
mv: overwrite '/apps/nginx/sbin/nginx'? y