本系列适合具备Linux基础的开发者,带你从零构建高并发网关实战能力
一、为什么选择Nginx?
1.1 现代架构的基石作用
graph LR
A[客户端] --> B[Nginx]
B --> C[负载均衡]
B --> D[静态资源]
B --> E[API网关]
C --> F[应用服务器1]
C --> G[应用服务器2]
1.2 关键性能优势对比
| 特性 | Nginx | Apache | Tomcat |
|---|---|---|---|
| 并发模型 | 事件驱动 | 进程/线程 | 阻塞I/O |
| 内存占用 | 10MB~50MB | 100MB+ | 200MB+ |
| 静态文件 | ⚡ 原生支持 | 需模块 | 不适用 |
| 反向代理 | ✅ 原生 | 需mod_proxy | 需配置 |
二、深入理解Nginx架构
2.1 Master-Worker进程模型
# 查看进程关系
$ pstree -p | grep nginx
|-nginx(1001)---nginx(1002)
|-nginx(1003)
|-nginx(1004)
-
Master进程
- 端口监听
- 信号处理(
kill -HUP 1001热重载) - 管理Worker生命周期
-
Worker进程
- 实际处理请求(每个Worker独立事件循环)
- CPU亲缘性绑定(
worker_cpu_affinity)
2.2 高性能核心机制
- Epoll事件驱动:百万级连接仅O(1)复杂度
- 零拷贝技术:
sendfile on减少内核态切换 - 内存池管理:避免频繁malloc/free
三、手把手安装实践(Ubuntu/CentOS双版本)
3.1 源码编译安装(推荐生产环境)
# 1. 安装依赖
$ apt install -y build-essential libpcre3 libpcre3-dev zlib1g-dev # Ubuntu
$ yum install -y gcc make pcre-devel zlib-devel # CentOS
# 2. 下载最新稳定版
$ wget https://nginx.org/download/nginx-1.24.0.tar.gz
$ tar -zxvf nginx-1.24.0.tar.gz
# 3. 编译配置(关键模块定制)
$ ./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \ # HTTPS支持
--with-http_v2_module \ # HTTP/2
--with-threads \ # 线程池
--with-file-aio # 异步文件IO
# 4. 编译安装
$ make -j$(nproc) && sudo make install
3.2 验证安装结果
# 启动服务
$ sudo /usr/local/nginx/sbin/nginx
# 检查端口
$ ss -tlnp | grep 80
LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=1120,fd=6))
# 测试访问
$ curl -I http://localhost
HTTP/1.1 200 OK
Server: nginx/1.24.0
四、核心配置文件拆解
4.1 骨架结构
# /usr/local/nginx/conf/nginx.conf
events {
worker_connections 1024; # 单Worker最大连接数
}
http {
# 全局配置
include mime.types;
default_type application/octet-stream;
# Server虚拟主机
server {
listen 80;
server_name localhost;
location / {
root html; # 静态资源目录
index index.html;
}
# 状态监控端点(慎用生产环境!)
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
}
4.2 关键配置说明
| 指令 | 作用 | 生产建议值 |
|---|---|---|
worker_processes | Worker进程数 | CPU核心数 |
keepalive_timeout | 长连接保持时间 | 65s |
gzip on; | 启用响应压缩 | 必须开启 |
access_log | 访问日志路径 | 按业务切割 |
五、性能调优首战
5.1 基础优化配置
events {
worker_connections 4096; # 提升连接数上限
use epoll; # Linux强制使用epoll
}
http {
sendfile on; # 零拷贝传输
tcp_nopush on; # 优化网络包发送
tcp_nodelay on; # 禁用Nagle算法
# 连接超时控制
keepalive_timeout 30s;
keepalive_requests 1000;
}
5.2 压测验证(使用wrk)
$ wrk -t4 -c1000 -d30s http://localhost
Running 30s test @ http://localhost
4 threads and 1000 connections
Requests/sec: 28476.34
Transfer/sec: 25.17MB