速卖通素材
奋斗

企业级Web服务(如Nginx、PostgreSQL)在Ubuntu Server上如何优化部署?

服务器

在 Ubuntu Server 上优化企业级 Web 服务(如 Nginx、PostgreSQL)的部署,需要从系统内核调优、资源隔离、安全加固、性能配置、监控运维等多个维度综合施策。以下是一套经过生产验证的优化方案:


一、操作系统层优化(Ubuntu Server)

1. 内核参数调优

编辑 /etc/sysctl.conf 或创建 /etc/sysctl.d/99-nginx-postgres.conf

# 网络栈优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.ip_local_port_range = 1024 65535

# 文件描述符限制(全局 + 用户级)
fs.file-max = 2097152
fs.inotify.max_user_watches = 524288

# PostgreSQL 专用(若内存充足)
vm.swappiness = 10
vm.vfs_cache_pressure = 50

应用生效:

sudo sysctl -p /etc/sysctl.d/99-nginx-postgres.conf

2. 用户与进程限制

编辑 /etc/security/limits.conf

* soft nofile 65535
* hard nofile 65535
postgres soft nproc unlimited
postgres hard nproc unlimited

确保 systemd 服务也继承该限制(见下文)。

3. 时间同步与电源管理

  • 启用 chrony 替代 ntp(更精准):
    sudo apt install chrony
    sudo systemctl enable --now chrony
  • 关闭节能模式(避免 CPU 降频):
    sudo apt install linux-tools-generic cpufrequtils
    echo "performance" | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

二、Nginx 优化策略

1. 编译选项(推荐从源码或 PPA 安装最新版)

使用官方 PPA 获取较新版本:

sudo add-apt-repository ppa:nginx/stable
sudo apt update && sudo apt install nginx

或编译时启用关键模块(--with-http_v2_module, --with-http_realip_module, --with-stream_module 等)。

2. 核心配置优化(/etc/nginx/nginx.conf

worker_processes auto;
worker_rlimit_nofile 65535;

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

http {
    # 缓存静态资源
    open_file_cache max=20000 inactive=60s;
    open_file_cache_valid 120s;
    open_file_cache_min_uses 2;

    # Gzip 压缩
    gzip on;
    gzip_types text/plain application/json application/javascript text/css image/svg+xml;
    gzip_comp_level 6;

    # TCP Fast Open & TLS Session Caching
    tcp_nopush on;
    tcp_nodelay on;

    # 连接复用与超时控制
    keepalive_timeout 65;
    keepalive_requests 10000;

    # 日志优化(异步写入)
    access_log /var/log/nginx/access.log combined buffer=32k flush=5s;
}

3. 站点级优化示例(/etc/nginx/sites-available/app.conf

server {
    listen 80 default_server;
    server_name example.com;

    # HTTP → HTTPS 重定向
    return 301 https://$host$request_uri;
}

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_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

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

    # 反向X_X + 缓冲优化
    location / {
        proxy_pass http://backend:8080;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 32k;
        proxy_busy_buffers_size 64k;
        proxy_read_timeout 120s;
        proxy_connect_timeout 10s;
    }

    # 健康检查端点
    location /health {
        access_log off;
        return 200 "OKn";
        add_header Content-Type text/plain;
    }
}

三、PostgreSQL 深度优化

1. 数据目录规划

  • 分离磁盘:将数据目录 (pgdata)、WAL 日志、临时文件放在不同物理盘/SSD。
  • RAID 建议:WAL 用 RAID 1(高可用),数据用 RAID 10(性能+冗余)。

2. postgresql.conf 关键调参(根据内存动态调整)

假设服务器有 32GB RAM,PG 分配 16GB:

shared_buffers = 4GB                    # 总内存 25%
effective_cache_size = 12GB             # 约 75%
work_mem = 256MB                        # 谨慎设置,防止 OOM
maintenance_work_mem = 2GB              # VACUUM/CREATE INDEX 用
wal_buffers = 64MB                      # 小事务高频写入场景可增至 256MB
checkpoint_completion_target = 0.9      # 平滑 I/O
max_wal_size = 8GB
min_wal_size = 2GB
random_page_cost = 1.1                  # SSD 环境降低此值
effective_io_concurrency = 200          # NVMe 可达 256+

✅ 提示:使用 pg_tune 工具生成初始配置:

sudo pg_config --bindir
/usr/lib/postgresql/15/bin/pg_tune --type database --memory 16G > /tmp/pg_tuned.conf

3. pg_hba.conf 安全加固

仅允许必要 IP 访问,禁用 trust 认证:

# IPv4 local connections:
hostssl all postgres 127.0.0.1/32 md5
hostssl all postgres ::1/128 md5

# 应用服务器网段(内部)
hostssl all app_user 10.0.0.0/24 scram-sha-256

4. 自动维护任务

启用 autovacuum 并定制:

autovacuum = on
autovacuum_vacuum_threshold = 50
autovacuum_analyze_threshold = 50
autovacuum_vacuum_scale_factor = 0.05
autovacuum_analyze_scale_factor = 0.01
autovacuum_max_workers = 3

四、容器化与编排(可选但推荐)

对于微服务架构,推荐使用 Docker + systemd 托管Kubernetes

Docker 最佳实践

# Nginx 精简镜像
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
RUN chown -R nginx:nginx /var/cache/nginx /var/log/nginx
USER nginx
CMD ["nginx", "-g", "daemon off;"]
# docker-compose.yml 片段
services:
  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_PASSWORD: ${DB_PASS}
    volumes:
      - pg_data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    ulimits:
      nofile:
        soft: 65535
        hard: 65535
    deploy:
      resources:
        limits:
          memory: 8G
          cpus: '4'
volumes:
  pg_data:

五、安全加固清单

类别 措施
访问控制 防火墙只开放必要端口(ufw allow from 10.0.0.0/24 to any port 5432);SSH 禁用密码登录,强制密钥认证
服务最小化 关闭不必要的 systemd 服务(systemctl disable bluetooth.service);Nginx 禁用 autoindexserver_tokens off
加密通信 TLS 1.3 强制开启;数据库连接启用 SSL(sslmode=require
审计日志 启用 auditd 记录敏感操作;Nginx/PG 日志集中到 ELK/Splunk
备份策略 pg_basebackup + WAL archiving;每日增量 + 每周全量;异地存储(S3/Rclone)

六、监控与告警

推荐工具栈:

  • 基础指标:Prometheus + Node Exporter + PG Exporter
  • 可视化:Grafana(预置 PostgreSQL Dashboard)
  • 日志:Filebeat → Loki → Grafana
  • 告警:Alertmanager 发送钉钉/邮件/Slack 通知

关键监控项:

  • Nginx:active_connections, requests/sec, upstream_response_time
  • PostgreSQL:backends, xact_commit/rollback, deadlocks, replication lag, buffer hit ratio

七、性能测试与压测验证

使用工具进行基准测试:

# Nginx 压力测试
wrk -t12 -c400 -d30s http://example.com/health

# PostgreSQL 基准
pgbench -i -s 1000 -T 60 -P 1 -f pgbench_custom.sql localhost testdb

关注指标:

  • 吞吐量(req/s)
  • P99 延迟
  • 错误率 < 0.1%
  • CPU/内存/IO 饱和度 < 80%

附:自动化部署脚本示例(Ansible 片段)

- name: Optimize PostgreSQL
  hosts: db_servers
  become: yes
  tasks:
    - name: Set sysctl for PG
      ansible.posix.sysctl:
        name: "{{ item.name }}"
        value: "{{ item.value }}"
        state: present
        reload: yes
      loop:
        - { name: 'vm.swappiness', value: '10' }
        - { name: 'net.core.somaxconn', value: '65535' }

    - name: Tune postgresql.conf
      template:
        src: templates/postgresql.conf.j2
        dest: /etc/postgresql/{{ pg_version }}/main/postgresql.conf
        owner: postgres
        group: postgres
        mode: '0640'
      notify: restart postgresql

最终建议
优化不是一次性工程,而应建立「配置即代码」(IaC)+「持续监控」+「定期压测」的闭环流程。初期可先聚焦 内核参数 + Nginx/TLS 配置 + PG 内存调优 三大杠杆点,快速提升 30%~50% 吞吐能力。

需要我针对具体场景(如:高并发 API 网关、实时分析型 DB、混合负载)提供定制化配置模板吗?

未经允许不得转载:轻量云Cloud » 企业级Web服务(如Nginx、PostgreSQL)在Ubuntu Server上如何优化部署?