参考资料

  1. NGINX 生产环境部署白皮书
  2. Ubuntu 环境的完整部署指南

Ubuntu 环境的完整部署指南

在 Ubuntu 上部署 NGINX,核心思路是利用其成熟的 apt 包管理生态和 systemd 服务框架,实现快速安装与标准化运维。以下是针对 Ubuntu 环境的完整部署指南。


📦 安装方式选择

Ubuntu 上安装 NGINX 有三种主流方式:

方式适用场景版本特点
Ubuntu 默认仓库开发、测试、快速验证版本较旧,由发行版维护
官方 NGINX 仓库生产环境(推荐)版本最新,更新可控
源码编译需要自定义模块最灵活,可集成第三方模块

生产环境强烈建议使用官方仓库,因为 Ubuntu 默认仓库中的 NGINX 版本通常滞后,且 F5/NGINX 无法验证其构建过程和更新频率。

从官方仓库安装(推荐)

# 1. 安装必要工具
sudo apt update
sudo apt install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring

# 2. 导入官方签名密钥
curl -fsSL https://nginx.org/keys/nginx_signing.key | \
  sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg

# 3. 添加官方仓库(稳定版)
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

# 4. 设置仓库优先级(优先使用官方源)
echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" | \
  sudo tee /etc/apt/preferences.d/99nginx

# 5. 安装
sudo apt update
sudo apt install -y nginx

从 Ubuntu 默认仓库安装(快速验证)

sudo apt update
sudo apt install -y nginx

安装完成后,NGINX 会自动启动并设置为开机自启。验证版本:

nginx -v

🛠️ 服务管理(systemd)

Ubuntu 使用 systemd 管理 NGINX 服务,常用命令如下:

# 查看服务状态
sudo systemctl status nginx

# 启动 / 停止 / 重启
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx

# 平滑重载配置(不中断服务)
sudo systemctl reload nginx

# 设置 / 取消开机自启
sudo systemctl enable nginx
sudo systemctl disable nginx

如果服务状态异常,首先检查配置语法:sudo nginx -t,然后查看错误日志 /var/log/nginx/error.log

🔥 防火墙配置(UFW)

Ubuntu 默认使用 UFW(Uncomplicated Firewall)。NGINX 安装时会在 UFW 中注册应用配置文件,可直接按名称放行。

# 安装并启用 UFW
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable

# 放行 SSH(避免被锁)
sudo ufw allow 'OpenSSH'

# 按应用配置文件放行 NGINX
sudo ufw allow 'Nginx Full'      # 同时开放 80 和 443(推荐)
# 或按需选择:
sudo ufw allow 'Nginx HTTP'      # 仅开放 80
sudo ufw allow 'Nginx HTTPS'     # 仅开放 443

# 查看状态
sudo ufw status

Nginx Full 配置文件会一次性开放 HTTP 和 HTTPS 端口,适合大多数生产场景。若需更细粒度控制,可直接指定端口:sudo ufw allow 8080:8090/tcp

📂 配置文件结构(Ubuntu 特有)

Ubuntu 上的 NGINX 配置遵循 sites-available / sites-enabled 模式,这与 Apache 的虚拟主机管理方式类似:

/etc/nginx/
├── nginx.conf              # 主配置文件
├── conf.d/                 # 额外配置片段(官方仓库安装时使用)
├── sites-available/        # 所有可用站点配置(存放配置文件的“仓库”)
│   └── default             # 默认站点
├── sites-enabled/          # 已启用站点(指向 sites-available 的符号链接)
│   └── default -> ../sites-available/default
├── snippets/               # 可复用的配置片段
├── mime.types              # MIME 类型映射
└── proxy_params            # 反向代理通用参数

启用一个新站点的标准流程:

# 1. 在 sites-available 创建配置
sudo nano /etc/nginx/sites-available/example.com

# 2. 创建符号链接到 sites-enabled
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 3. 测试并重载
sudo nginx -t && sudo systemctl reload nginx

🌐 站点配置(Server Block)

一个基础的静态站点配置示例:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example.com/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
        access_log off;
    }

    # 日志
    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;
}

若需托管多个域名,只需为每个域名在 sites-available/ 中创建独立配置文件,再分别建立符号链接即可。

🔒 HTTPS 配置(Let's Encrypt / Certbot)

Ubuntu 上获取免费 SSL 证书的标准工具是 Certbot

# 安装 Certbot 和 NGINX 插件
sudo apt install -y certbot python3-certbot-nginx

# 自动获取证书并修改 NGINX 配置
sudo certbot --nginx -d example.com -d www.example.com

# 测试自动续期
sudo certbot renew --dry-run

Certbot 会自动修改 NGINX 配置,将 listen 80 改为 listen 443 ssl,并注入证书路径。证书默认存储在 /etc/letsencrypt/live/example.com/ 目录下,其中 fullchain.pem 已包含中间证书。

手动配置 HTTPS 时,推荐的安全参数:

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

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    # HSTS
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
}

# HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

🔄 反向代理配置

Ubuntu 的 /etc/nginx/proxy_params 文件预置了常用的代理头部,可直接在配置中 include 引用:

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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 3s;
        proxy_read_timeout   30s;
    }

    # 静态资源直接由 NGINX 处理
    location /static/ {
        alias /var/www/app/static/;
        expires 30d;
    }
}

若后端应用运行在 Unix Socket 上(常见于 PHP-FPM),可改为 proxy_pass http://unix:/run/php/php8.3-fpm.sock:/;

📊 日志管理与轮转

Ubuntu 上 NGINX 日志默认位于 /var/log/nginx/,其中 access.log 记录请求详情,error.log 记录错误信息。

Ubuntu 自带的 logrotate 会自动轮转 NGINX 日志。官方包提供的配置位于 /etc/logrotate.d/nginx,生产环境可按需加固:

sudo nano /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 `cat /var/run/nginx.pid`
        fi
    endscript
}

关键点:postrotate 中的 kill -USR1 通知 NGINX 重新打开日志文件,否则 NGINX 会继续写入已被轮转的旧文件。测试配置:

sudo logrotate -d /etc/logrotate.d/nginx   # 调试模式
sudo logrotate -f /etc/logrotate.d/nginx   # 强制执行

⚡ 性能调优(Ubuntu 视角)

内核参数

Ubuntu 的 sysctl 配置方式与通用 Linux 一致,编辑 /etc/sysctl.conf/etc/sysctl.d/ 下的独立文件:

net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
fs.file-max = 200000

执行 sudo sysctl -p 生效。

NGINX 主配置

worker_processes auto;
worker_rlimit_nofile 65535;

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

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml;
    gzip_min_length 1024;
    gzip_comp_level 5;
}

Ubuntu 上 worker_processes auto 会自动匹配 CPU 核心数,避免手动调整的麻烦。worker_rlimit_nofile 必须大于 worker_connections,否则会触发 too many open files 错误。

🛡️ 安全加固(Ubuntu 特色)

系统层

# 定期更新系统和 NGINX
sudo apt update && sudo apt upgrade -y

# 启用 unattended-upgrades 自动安全更新
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Ubuntu 会通过 USN(Ubuntu Security Notice) 发布 NGINX 安全更新。例如 USN-7285-1 修复了 NGINX 中多个安全漏洞,影响 Ubuntu 20.04/22.04/24.10。保持 apt upgrade 习惯即可及时覆盖这些补丁。

NGINX 层

# 隐藏版本信息
server_tokens off;

# 安全响应头
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;

# 限制敏感目录
location ~ /\.(git|ht|env|svn) {
    deny all;
    return 404;
}

Fail2Ban 集成(可选)

Ubuntu 上可安装 Fail2Ban 自动封禁恶意 IP:

sudo apt install -y fail2ban
sudo systemctl enable fail2ban

Fail2Ban 可读取 NGINX 的 access.log,对频繁出现 401/403/404 的 IP 自动添加 UFW 规则进行封禁。

🔍 故障排查速查

# 配置语法检查
sudo nginx -t

# 查看错误日志(实时)
sudo tail -f /var/log/nginx/error.log

# 查看服务状态
sudo systemctl status nginx

# 检查端口监听
sudo ss -tlnp | grep nginx

# 检查 AppArmor 是否阻止 NGINX 出站连接
sudo journalctl -xe | grep -i apparmor

Ubuntu 的 AppArmor 可能阻止 NGINX 建立出站连接(尤其在 Ubuntu 24.04 升级后出现 502 错误的场景中)。如遇此类问题,检查 journalctl 中的 AppArmor 拒绝记录,或临时将 NGINX 的 AppArmor 配置文件设为 complain 模式进行排查。

📋 Ubuntu 部署检查清单

检查项命令 / 配置
NGINX 已安装且版本正确nginx -v
服务开机自启systemctl is-enabled nginx
配置语法通过sudo nginx -t
UFW 已放行 80/443sudo ufw status
站点符号链接已创建ls -la /etc/nginx/sites-enabled/
日志轮转已配置cat /etc/logrotate.d/nginx
系统安全更新已应用sudo apt list --upgradable
SSL 证书自动续期正常sudo certbot renew --dry-run
AppArmor 未阻止出站连接sudo journalctl -xe | grep -i apparmor

在 Ubuntu 上,NGINX 的部署优势在于包管理的一致性和 systemd 的标准化,配合 UFW、Certbot、logrotate、Fail2Ban 等原生工具,可以快速搭建一套生产可用的 Web 服务环境。

作者:王壹杰
时间:2026-09-10 21:27:21
来源:https://docker.ciilii.com/