Nginx详解与部署流程

在项目初期,如果并发量较小,用户数量有限,通常只需通过一个jar包启动应用,内部由自带的Tomcat处理请求即可满足需求。但随着用户量和并发量的提升,单一应用实例可能无法承载全部流量,这时就需要引入Nginx进行负载均衡和反向代理,提升系统的可用性和扩展性。

为什么选择Nginx

Nginx(engine x)是一款高性能的HTTP和反向代理Web服务器,同时也支持IMAP/POP3/SMTP等邮件服务。其主要优点包括:

  • 占用内存少,并发处理能力强
  • 安装简单,配置文件简洁明了(支持Perl语法)
  • 稳定性高,BUG极少
  • 支持热部署,几乎可以做到不间断运行
  • 官方测试数据显示,Nginx可支持高达5万并发连接

Nginx的主要作用

  1. 正向代理
    例如VPN,帮助用户访问外部服务器,起到”跳板”作用。

  2. 反向代理
    由Nginx作为前端服务器,接收用户请求后转发给后端应用服务器,实现统一入口和安全隔离。

  3. 负载均衡
    Nginx内置多种负载均衡策略(如轮询、加权轮询、ip_hash),也支持自定义扩展策略,能够将流量均匀分发到多台后端服务器,提高系统整体吞吐量和可用性。

  4. 动静分离
    将静态资源(如css、html、jpg、js等)与动态请求分离,静态资源直接由Nginx处理并缓存,动态请求转发给后端应用服务器,极大提升响应速度和系统性能。

Nginx部署操作流程

下面以CentOS为例,介绍Nginx的基本部署流程:

1. 安装Nginx

方式一:使用yum安装(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 添加Nginx官方yum源
sudo tee /etc/yum.repos.d/nginx.repo <<EOF
[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
EOF

# 安装Nginx
sudo yum install nginx -y

# 启动Nginx并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

方式二:源码编译安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 安装依赖包
sudo yum install -y gcc gcc-c++ pcre-devel zlib-devel openssl-devel

# 下载Nginx源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 配置编译选项
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_stub_status_module \
--with-http_auth_request_module \
--with-threads \
--with-stream \
--with-stream_ssl_module \
--with-http_slice_module \
--with-file-aio \
--with-http_v2_module

# 编译安装
make && make install

2. Nginx配置文件详解

Nginx的主配置文件通常位于 /etc/nginx/nginx.conf,主要包含以下结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 全局配置块
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# events块
events {
worker_connections 1024;
use epoll;
}

# http块
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;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;

# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}

3. 常用Nginx命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 启动Nginx
nginx
# 或使用systemctl
systemctl start nginx

# 停止Nginx
nginx -s stop
# 或使用systemctl
systemctl stop nginx

# 重新加载配置
nginx -s reload
# 或使用systemctl
systemctl reload nginx

# 检查配置文件语法
nginx -t

# 查看Nginx版本
nginx -v

# 查看Nginx进程
ps aux | grep nginx

# 查看Nginx端口占用
netstat -tlnp | grep nginx

4. 反向代理配置示例

创建一个反向代理配置文件 /etc/nginx/conf.d/proxy.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
listen 80;
server_name example.com;

# 反向代理到后端应用
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

# 超时设置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}

# 静态资源处理
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
root /var/www/html;
}
}

# 后端服务器组
upstream backend_servers {
server 192.168.1.10:8080 weight=1;
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=1;
}

5. 负载均衡策略配置

Nginx支持多种负载均衡策略:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

upstream backend_weighted {
# 加权轮询
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 weight=1;
}

upstream backend_ip_hash {
# IP哈希
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

upstream backend_least_conn {
# 最少连接数
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

6. 动静分离配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
listen 80;
server_name example.com;

# 静态资源目录
location /static/ {
alias /var/www/static/;
expires 1y;
add_header Cache-Control "public, immutable";

# 开启gzip压缩
gzip_static on;
}

# 动态请求转发
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

7. SSL/HTTPS配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl http2;
server_name example.com;

# SSL证书配置
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

# SSL安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# HSTS头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}

8. 性能优化配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 全局优化
worker_processes auto;
worker_rlimit_nofile 65535;

events {
worker_connections 65535;
use epoll;
multi_accept on;
}

http {
# 文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

# 客户端优化
client_max_body_size 10m;
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;

# 代理缓冲
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;

# 超时设置
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
}

9. 监控和日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 状态监控页面
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}

# 自定义日志格式
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';

10. 常见问题排查

检查Nginx状态

1
2
3
4
5
6
7
8
9
10
11
# 检查配置文件语法
nginx -t

# 查看错误日志
tail -f /var/log/nginx/error.log

# 查看访问日志
tail -f /var/log/nginx/access.log

# 检查端口占用
netstat -tlnp | grep :80

性能测试

1
2
3
4
5
# 使用ab进行压力测试
ab -n 1000 -c 100 http://example.com/

# 使用wrk进行性能测试
wrk -t12 -c400 -d30s http://example.com/

总结

Nginx作为高性能的Web服务器和反向代理,在现代Web架构中扮演着重要角色。通过合理的配置和优化,可以显著提升系统的性能、可用性和安全性。在实际部署中,需要根据具体的业务需求和服务器资源情况,选择合适的配置方案。

关键要点:

  • 合理配置worker进程数和连接数
  • 启用gzip压缩减少传输大小
  • 配置适当的缓存策略
  • 实现动静分离提升性能
  • 配置SSL证书保证安全性
  • 定期监控和优化性能指标