直接装包管理器默认版本虽可运行,但Ubuntu 22.04的1.18.x不支持HTTP/2和现代TLS,高并发下易卡SSL握手或报502;必须换官方源(如nginx.org/jammy)、升至1.24.0+,并调worker_processes auto、worker_rlimit_nofile 65535、events中use epoll与multi_accept on,同步配置系统limits和SELinux/firewalld。

直接装包管理器版本能跑起来,但默认配置扛不住高并发;真要压测过万连接、做反向代理或 HTTPS 终止,必须调参数+换源+改用户权限,否则 nginx -t 通过了也撑不住真实流量。
Ubuntu/Debian 装新版 Nginx 别用默认源
Ubuntu 22.04 默认 apt install nginx 装的是 1.18.x,不支持 http_v2_module 和现代 TLS 配置。高并发场景下容易在 SSL 握手阶段卡住或触发 502 Bad Gateway。
- 先导入官方 GPG 密钥:
curl https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg - 添加稳定版源(Ubuntu 22.04 对应
jammy):echo "deb [arch=amd64 signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu/ jammy nginx" | sudo tee /etc/apt/sources.list.d/nginx.list - 锁版本防误升:
echo -e "Package: *\nPin: origin nginx.org\nPin-Priority: 900" | sudo tee /etc/apt/preferences.d/90nginx - 再更新安装:
sudo apt update && sudo apt install nginx -y
装完执行 nginx -v,确认输出是 nginx version: nginx/1.24.0 或更高——低于 1.22 的版本在 epoll 事件模型和 reuseport 支持上存在已知瓶颈。
CentOS/RHEL 系必须启用 EPEL + 官方源
CentOS Stream 9 或 AlmaLinux 9 默认仓库里 Nginx 版本太旧,且缺 http_ssl_module 编译项,ssl_protocols TLSv1.3 直接报错。
- 先装 EPEL:
sudo dnf install epel-release -y - 再加 Nginx 官方源:
sudo dnf config-manager --add-repo https://nginx.org/packages/rhel/9/nginx.repo - 禁用系统自带源冲突:
sudo dnf module reset nginx && sudo dnf module enable nginx:1.24 - 安装:
sudo dnf install nginx -y
注意:不要用 dnf install nginx-mod-http-* 单独装模块,官方二进制包已内置全部常用模块,手动加载反而容易引发 module "http_ssl_module" is not binary compatible 错误。
高并发必须改的三个核心配置项
默认 /etc/nginx/nginx.conf 是为单页静态站设计的,开 1000 连接就可能触发 accept() failed (24: Too many open files)。
-
worker_processes auto;—— 必须设为auto,不能写死数字;否则多核 CPU 下worker_connections实际生效值会受限 -
worker_rlimit_nofile 65535;—— 配合系统级限制一起调,否则worker_connections再大也没用 -
events { use epoll; worker_connections 4096; multi_accept on; }——epoll是 Linux 必选项,multi_accept on让 worker 一次收多个新连接,减少 syscall 开销
还要同步调系统限制:echo 'nginx soft nofile 65535' | sudo tee -a /etc/security/limits.conf,然后重启 systemctl daemon-reload 并重载 nginx。
启动前务必检查端口占用和 SELinux 状态
CentOS/RHEL 上常见问题不是配置写错,而是 80/443 被 firewalld 拦住,或 SELinux 拒绝 nginx 绑定网络端口,日志里只显示 bind() to 0.0.0.0:80 failed (13: Permission denied),不提 SELinux。
- 查端口:
sudo ss -tlnp | grep -E ':80|:443',确认没被httpd或docker占用 - 关防火墙临时验证:
sudo systemctl stop firewalld(生产环境请用firewall-cmd --permanent --add-service=http) - SELinux 临时放行:
sudo setsebool -P httpd_can_network_bind 1;若用自定义路径(如/data/www),还得加sudo semanage fcontext -a -t httpd_sys_content_t "/data/www(/.*)?"再restorecon -Rv /data/www
最后执行 sudo nginx -t 成功后,别直接 systemctl start nginx,先手动跑一次:sudo /usr/sbin/nginx -c /etc/nginx/nginx.conf,看终端是否静默退出——很多“启动成功”其实是 fork 失败后父进程假退出。











