插件窝 干货文章 VPS服务器优化: NGINX和PM2的最佳实践

VPS服务器优化: NGINX和PM2的最佳实践

优化 NGINX PM2 配置 288    来源:    2025-04-11

VPS服务器优化:NGINX和PM2最佳实践

1. NGINX优化配置

基础性能优化

# 工作进程配置
worker_processes auto; # 自动匹配CPU核心数
worker_rlimit_nofile 100000; # 每个worker能打开的文件描述符数量

events {
    worker_connections 4096; # 每个worker的最大连接数
    multi_accept on; # 一次接受所有新连接
    use epoll; # Linux高效事件模型
}

http {
    # 基本性能参数
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    keepalive_requests 1000;
    reset_timedout_connection on;

    # 缓冲区优化
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 4 4k;

    # MIME类型缓存
    include mime.types;
    default_type application/octet-stream;

    # 日志优化
    access_log off; # 生产环境可关闭或限制
    error_log /var/log/nginx/error.log crit;

    # Gzip压缩
    gzip on;
    gzip_min_length 10240;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
    gzip_disable "MSIE [1-6]\.";

    # 静态文件缓存
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

安全加固配置

server {
    # 禁用不必要的HTTP方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # 隐藏服务器信息
    server_tokens off;

    # 安全头部
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
    add_header Referrer-Policy "strict-origin-when-cross-origin";
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

    # 防止点击劫持
    add_header X-Frame-Options "DENY";

    # SSL优化配置(如果使用HTTPS)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;
}

2. PM2优化配置

基础配置

# 安装PM2
npm install pm2 -g

# 启动应用(示例)
pm2 start app.js -i max --name "MyApp" --max-memory-restart 300M

常用命令

# 查看运行中的应用
pm2 list

# 监控资源使用
pm2 monit

# 查看日志
pm2 logs

# 保存当前进程列表
pm2 save

# 设置开机启动
pm2 startup

高级配置(ecosystem.config.js)

module.exports = {
  apps: [{
    name: 'MyApp',
    script: 'app.js',
    instances: 'max', // 根据CPU核心数自动扩展
    exec_mode: 'cluster', // 集群模式
    autorestart: true,
    watch: false,
    max_memory_restart: '1G', // 内存超过1G自动重启
    env: {
      NODE_ENV: 'development'
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }]
};

性能监控

# 安装PM2监控模块
pm2 install pm2-server-monit

# 查看详细指标
pm2 show <app_name>

3. 系统级优化

内核参数调整(/etc/sysctl.conf)

# 增加TCP连接数
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1

# 增加文件描述符限制
fs.file-max = 2097152
fs.nr_open = 2097152

# 网络栈优化
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 32768
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_max_tw_buckets = 1000000
net.ipv4.tcp_keepalive_time = 30
net.ipv4.tcp_keepalive_intvl = 10
net.ipv4.tcp_keepalive_probes = 3

# 内存管理
vm.swappiness = 10
vm.overcommit_memory = 1

应用配置后执行:

sysctl -p

文件描述符限制(/etc/security/limits.conf)

* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535

4. 监控与维护

基础监控工具

# 安装基础工具
apt install htop iotop iftop nmon -y

# 实时监控
htop        # CPU/内存
iftop       # 网络流量
iotop       # 磁盘IO
nmon        # 综合监控

日志轮转配置(/etc/logrotate.d/nginx)

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

5. 常见问题解决方案

NGINX 502 Bad Gateway

  1. 检查后端服务(如PM2)是否运行
  2. 增加代理超时时间: nginx proxy_connect_timeout 60s; proxy_read_timeout 60s; proxy_send_timeout 60s;
  3. 检查文件描述符限制

PM2内存泄漏

  1. 设置内存限制自动重启: bash pm2 start app.js --max-memory-restart 500M
  2. 使用PM2的集群模式分散负载
  3. 定期重启应用: bash pm2 restart app --cron-restart="0 0 * * *"

高并发下性能问题

  1. 调整NGINX的worker_connections和worker_processes
  2. 优化内核参数(见第3部分)
  3. 使用HTTP/2协议
  4. 考虑添加负载均衡层

通过以上优化配置,您的VPS服务器应该能够更高效地运行NGINX和PM2,提供更好的性能和稳定性。