Nginx源码编译安装与生产级配置实战:从入门到精通
作者:WAKE UP技术
公众号:WAKE UP技术
技术博客:blog.lweiqiang.xyz
前言
在生产环境中,直接使用 apt install nginx 虽然方便,但你无法掌控编译模块、优化参数和安全配置。作为运维工程师,我们需要对每一行配置、每一个模块了如指掌。
本文将从运维架构师视角,手把手教你源码编译安装 Nginx 1.28,涵盖:
- • ✅ FHS 标准目录结构规划
- • ✅ 生产级编译参数配置
- • ✅ Stream 四层代理与 SNI 分流
- • ✅ SSL/TLS 性能优化
- • ✅ Systemd 守护进程配置
- • ✅ 详细排错指南
一、环境准备
1.1 系统要求
- • 操作系统: Debian 12 / Ubuntu 22.04+(CentOS/RHEL 需调整包管理命令)
- • 内核版本: Linux 5.10+
- • 磁盘空间: 至少 2GB 可用空间
- • 内存: 建议 2GB+
1.2 安装编译依赖
# 更新系统包索引
sudo apt update -y
# 安装编译工具链和依赖库
sudo apt install -y build-essential libpcre3-dev zlib1g-dev libssl-dev \
libxslt1-dev libgd-dev libgeoip-dev libgoogle-perftools-dev
依赖说明:
| 包名 | 作用 |
|---|---|
build-essential |
GCC 编译器、Make 工具 |
libpcre3-dev |
正则表达式库(rewrite 模块必需) |
zlib1g-dev |
压缩库(gzip 模块必需) |
libssl-dev |
SSL/TLS 支持 |
libxslt1-dev |
XSLT 转换支持 |
libgd-dev |
图像处理(image_filter 模块) |
libgeoip-dev |
GeoIP 地理位置支持 |
二、创建 FHS 标准目录结构
遵循 Filesystem Hierarchy Standard (FHS) 标准,便于后续管理和维护:
# 1. 创建配置和站点目录
sudo mkdir -p /etc/nginx/{conf.d,sites-available,sites-enabled,ssl}
# 2. 创建日志目录
sudo mkdir -p /var/log/nginx
# 3. 创建临时文件目录(用于上传、代理缓存等)
sudo mkdir -p /var/lib/nginx/{client_body,proxy,fastcgi,uwsgi,scgi}
# 4. 设置目录权限
sudo chown -R www-data:root /var/log/nginx /var/lib/nginx
sudo chmod -R 700 /var/lib/nginx
目录结构说明:
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 通用配置片段
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用站点配置(软链接)
└── ssl/ # SSL 证书存放
/var/log/nginx/ # 日志文件
/var/lib/nginx/ # 运行时临时文件
三、下载源码并编译安装
3.1 下载 Nginx 源码
# 进入源码目录
cd /usr/src
# 下载 Nginx 1.28.2 稳定版(截至2026年3月最新稳定版)
sudo wget https://nginx.org/download/nginx-1.28.2.tar.gz
# 解压源码包
sudo tar -xzf nginx-1.28.2.tar.gz
cd nginx-1.28.2
3.2 配置编译参数
这是最关键的一步!生产级编译参数决定了 Nginx 的功能和性能:
sudo ./configure \
--prefix=/usr/share/nginx \
--sbin-path=/usr/sbin/nginx \
--modules-path=/usr/lib/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=/run/nginx.pid \
--lock-path=/run/nginx.lock \
--http-client-body-temp-path=/var/lib/nginx/client_body \
--http-proxy-temp-path=/var/lib/nginx/proxy \
--http-fastcgi-temp-path=/var/lib/nginx/fastcgi \
--http-uwsgi-temp-path=/var/lib/nginx/uwsgi \
--http-scgi-temp-path=/var/lib/nginx/scgi \
--user=www-data \
--group=www-data \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_v3_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-http_xslt_module \
--with-http_image_filter_module \
--with-http_geoip_module \
--with-http_perl_module \
--with-threads \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-stream_geoip_module \
--with-stream_ssl_preread_module \
--with-google_perftools_module \
--with-compat \
--with-file-aio \
--with-http_degradation_module \
--with-http_slice_module \
--with-mail \
--with-mail_ssl_module
核心模块说明:
| 模块 | 功能 |
|---|---|
--with-http_ssl_module |
HTTPS 支持 |
--with-http_v2_module |
HTTP/2 支持 |
--with-http_v3_module |
HTTP/3 (QUIC) 支持 |
--with-stream |
TCP/UDP 四层代理 |
--with-stream_ssl_preread_module |
SNI 预读(实现端口复用) |
--with-http_realip_module |
获取真实客户端 IP |
3.3 编译并安装
# 使用多核并行编译(-j$(nproc) 自动检测 CPU 核心数)
sudo make -j$(nproc)
# 安装
sudo make install
编译时间约 2-5 分钟,取决于服务器性能。
四、生产级主配置文件
4.1 创建 nginx.conf
sudo tee /etc/nginx/nginx.conf > /dev/null << 'EOF'
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /run/nginx.pid;
# 加载动态模块
load_module modules/ngx_http_geoip_module.so;
load_module modules/ngx_stream_module.so;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
# 隐藏版本号(安全加固)
server_tokens off;
# MIME 类型
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式(JSON 格式,便于 ELK/Loki 收集)
log_format json_combined escape=json
'{"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"http_x_forwarded_for":"$http_x_forwarded_for",'
'"server_name":"$server_name",'
'"upstream_addr":"$upstream_addr",'
'"upstream_response_time":"$upstream_response_time"}';
access_log /var/log/nginx/access.log json_combined;
error_log /var/log/nginx/error.log warn;
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
# 虚拟主机配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
# Stream 模块(四层代理)
stream {
log_format stream_json escape=json
'{"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"protocol":"$protocol",'
'"status":"$status",'
'"bytes_sent":$bytes_sent,'
'"bytes_received":$bytes_received,'
'"session_time":"$session_time",'
'"upstream_addr":"$upstream_addr"}';
access_log /var/log/nginx/stream-access.log stream_json;
error_log /var/log/nginx/stream-error.log warn;
# SNI 预读映射(实现 443 端口复用)
map $ssl_preread_server_name $backend {
default web_backend;
git.example.com git_backend;
db.example.com db_backend;
}
upstream web_backend {
server 127.0.0.1:8443;
}
upstream git_backend {
server 127.0.0.1:3000;
}
upstream db_backend {
server 127.0.0.1:5432;
}
server {
listen 443;
proxy_pass $backend;
ssl_preread on;
}
}
EOF
4.2 创建默认站点配置
sudo tee /etc/nginx/sites-available/default > /dev/null << 'EOF'
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 状态监控页面(限制访问)
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
}
EOF
# 启用默认站点
sudo ln -sf /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
# 创建默认网页目录
sudo mkdir -p /var/www/html
sudo chown -R www-data:www-data /var/www/html
五、配置 Systemd 服务
5.1 创建服务文件
sudo tee /etc/systemd/system/nginx.service > /dev/null << 'EOF'
[Unit]
Description=A high performance web server and a reverse proxy server
Documentation=man:nginx(8)
After=network.target nss-lookup.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;'
ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;'
ExecReload=/usr/sbin/nginx -g 'daemon on; master_process on;' -s reload
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid
TimeoutStopSec=5
KillMode=mixed
[Install]
WantedBy=multi-user.target
EOF
5.2 启动并启用服务
# 重载 Systemd 配置
sudo systemctl daemon-reload
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 查看状态
sudo systemctl status nginx
六、验证安装
6.1 检查版本和编译参数
# 查看版本
nginx -v
# 查看详细编译参数
nginx -V
预期输出:
nginx version: nginx/1.28.2
built by gcc 12.2.0 (Debian 12.2.0-14)
built with OpenSSL 3.0.11 19 Sep 2023
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx ...
6.2 测试配置文件语法
sudo nginx -t
预期输出:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
6.3 访问测试
# 本地测试
curl -I http://localhost
# 预期输出
HTTP/1.1 200 OK
Server: nginx
七、详细排错指南
7.1 配置文件语法错误
症状:
nginx: [emerg] unknown directive "stream" in /etc/nginx/nginx.conf:50
原因: 编译时未添加 --with-stream 模块
解决:
# 1. 重新编译,确保包含 stream 模块
cd /usr/src/nginx-1.28.2
sudo ./configure --with-stream --with-stream_ssl_module [其他参数...]
sudo make -j$(nproc) && sudo make install
# 2. 重启服务
sudo systemctl restart nginx
7.2 端口被占用
症状:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
排查:
# 查看占用 80 端口的进程
sudo ss -tulpn | grep :80
# 或
sudo lsof -i :80
解决:
# 停止冲突服务
sudo systemctl stop apache2
# 或修改 Nginx 监听端口
sudo sed -i 's/listen 80/listen 8080/' /etc/nginx/sites-available/default
sudo systemctl restart nginx
7.3 权限不足
症状:
nginx: [emerg] mkdir() "/var/lib/nginx/client_body" failed (13: Permission denied)
排查:
# 检查目录权限
ls -la /var/lib/nginx/
ls -la /var/log/nginx/
解决:
# 修复权限
sudo chown -R www-data:root /var/log/nginx /var/lib/nginx
sudo chmod -R 700 /var/lib/nginx
# 重启服务
sudo systemctl restart nginx
7.4 SSL/TLS 握手失败
症状: 浏览器显示 “ERR_SSL_PROTOCOL_ERROR”
排查:
# 检查证书文件
sudo openssl x509 -in /etc/nginx/ssl/cert.pem -text -noout
# 测试 SSL 连接
openssl s_client -connect localhost:443 -servername example.com
解决:
# 确保证书文件存在且权限正确
sudo ls -la /etc/nginx/ssl/
# 证书权限应为 644,私钥应为 600
sudo chmod 644 /etc/nginx/ssl/cert.pem
sudo chmod 600 /etc/nginx/ssl/key.pem
7.5 服务启动失败(Systemd)
症状:
Job for nginx.service failed because the control process exited with error code.
排查:
# 查看详细错误信息
sudo systemctl status nginx -l
# 查看日志
sudo journalctl -u nginx -n 50 --no-pager
# 查看 Nginx 错误日志
sudo tail -f /var/log/nginx/error.log
常见解决:
# 1. 检查配置文件语法
sudo nginx -t
# 2. 检查 PID 文件权限
sudo touch /run/nginx.pid
sudo chown www-data:www-data /run/nginx.pid
# 3. 重新加载 Systemd
sudo systemctl daemon-reload
sudo systemctl restart nginx
7.6 性能问题排查
症状: 高并发时响应缓慢
排查:
# 查看连接数
ss -s
# 查看 Nginx 工作进程
ps aux | grep nginx
# 查看系统限制
ulimit -n
优化:
# 1. 增加文件描述符限制
sudo tee -a /etc/security/limits.conf << EOF
www-data soft nofile 65535
www-data hard nofile 65535
EOF
# 2. 调整内核参数
sudo tee -a /etc/sysctl.conf << EOF
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
EOF
sudo sysctl -p
八、生产环境最佳实践
8.1 安全加固清单
- • [ ] 隐藏 Nginx 版本号 (
server_tokens off) - • [ ] 禁用不安全的 HTTP 方法
- • [ ] 配置 HTTPS 并启用 HSTS
- • [ ] 设置合理的请求体大小限制
- • [ ] 配置访问日志和错误日志
- • [ ] 限制敏感目录访问
- • [ ] 启用防火墙(UFW/iptables)
8.2 监控指标
| 指标 | 命令 | 说明 |
|---|---|---|
| 活跃连接数 | curl http://localhost/nginx_status |
实时连接状态 |
| 请求速率 | 分析 access.log | QPS/TPS |
| 响应时间 | $request_time 字段 |
平均响应时间 |
| 错误率 | 分析 error.log | 5xx 错误比例 |
8.3 备份策略
# 备份配置文件
sudo tar -czf nginx-config-$(date +%Y%m%d).tar.gz /etc/nginx/
# 备份 SSL 证书
sudo tar -czf nginx-ssl-$(date +%Y%m%d).tar.gz /etc/nginx/ssl/
# 定期备份脚本(加入 crontab)
0 2 * * * /path/to/backup-script.sh
总结
通过本文,你已经学会了:
- 1. ✅ 源码编译安装 Nginx 1.28,完全掌控编译模块
- 2. ✅ FHS 标准目录 规划,便于后续维护
- 3. ✅ 生产级配置,包括 HTTP/2、HTTP/3、Stream 代理
- 4. ✅ Systemd 服务 管理,确保服务稳定运行
- 5. ✅ 详细排错指南,快速定位和解决问题
关键要点:
- • 生产环境务必使用明确版本标签,避免
latest - • 配置文件通过 Volume 挂载,不打包进镜像
- • 单容器只运行单进程,便于管理和监控
- • 实施健康检查和资源限制
💡 温馨提示: 执行任何系统级操作前,请确保在测试环境验证,并备份重要数据。
关于作者
- • 作者:WAKE UP技术
- • 公众号:WAKE UP技术(扫码关注获取更多运维实战文章)
- • 个人主页:lweiqiang.xyz
- • 技术博客:blog.lweiqiang.xyz
本文首发于 WAKE UP技术 公众号,转载请注明出处。
夜雨聆风