插件窝 干货文章 高级教程: 使用NGINX和PM2优化VPS服务器的性能

高级教程: 使用NGINX和PM2优化VPS服务器的性能

NGINX sudo http 配置 813    来源:    2025-04-11

使用NGINX和PM2优化VPS服务器性能的高级教程

1. 系统基础优化

1.1 系统更新与基础配置

# 更新系统软件包
sudo apt update && sudo apt upgrade -y

# 安装常用工具
sudo apt install -y htop nload net-tools git build-essential

1.2 内核参数优化

编辑 /etc/sysctl.conf 文件,添加以下内容:

# 增加网络性能
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30

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

应用修改:

sudo sysctl -p

2. NGINX高级配置

2.1 安装最新版NGINX

# 添加官方仓库
sudo apt install -y curl gnupg2 ca-certificates lsb-release
echo "deb http://nginx.org/packages/mainline/ubuntu `lsb_release -cs` nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -

# 安装NGINX
sudo apt update
sudo apt install -y nginx

2.2 优化NGINX配置

编辑 /etc/nginx/nginx.conf 主配置文件:

user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;

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

http {
    # 基础设置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

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

    # MIME类型
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for"';

    # Gzip压缩
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 包含其他配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

2.3 网站服务器配置示例

创建 /etc/nginx/sites-available/yourdomain.com:

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

    # 重定向HTTP到HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;

    # SSL证书配置
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;

    # SSL优化
    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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # 根目录设置
    root /var/www/yourdomain.com/public;
    index index.html index.htm index.php;

    # 日志
    access_log /var/log/nginx/yourdomain.com.access.log main;
    error_log /var/log/nginx/yourdomain.com.error.log warn;

    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf|svg)$ {
        expires 365d;
        add_header Cache-Control "public, no-transform";
    }

    # PHP处理 (如果需要)
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }

    # 反向代理Node.js应用示例
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_cache_bypass $http_upgrade;
    }
}

启用配置:

sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

3. PM2高级配置

3.1 安装Node.js和PM2

# 使用NVM安装Node.js
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts

# 全局安装PM2
npm install -g pm2

3.2 PM2高级配置

创建PM2生态系统文件 ecosystem.config.js:

module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js', // 或 'npm start'

    // 高级设置
    instances: 'max', // 使用所有CPU核心
    exec_mode: 'cluster', // 集群模式
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',

    // 日志设置
    log_date_format: 'YYYY-MM-DD HH:mm Z',
    error_file: '/var/log/pm2/my-app-error.log',
    out_file: '/var/log/pm2/my-app-out.log',
    pid_file: '/var/log/pm2/my-app.pid',

    // 环境变量
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }],

  // 部署配置 (可选)
  deploy: {
    production: {
      user: 'deploy',
      host: ['your-server-ip'],
      ref: 'origin/main',
      repo: 'git@github.com:your/repo.git',
      path: '/var/www/production',
      'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production'
    }
  }
};

3.3 PM2常用命令

# 启动应用
pm2 start ecosystem.config.js --env production

# 查看运行中的应用
pm2 list

# 监控资源使用
pm2 monit

# 查看日志
pm2 logs

# 保存当前进程列表
pm2 save

# 设置开机启动
pm2 startup
pm2 save

# 零停机重载
pm2 reload all

# 集群操作
pm2 scale my-app +2 # 增加2个实例
pm2 scale my-app 4   # 设置4个实例

4. 高级性能优化技巧

4.1 启用Brotli压缩

在NGINX中启用Brotli压缩(比Gzip更高效):

# 安装Brotli模块
sudo apt install -y brotli libbrotli-dev
cd /usr/src
sudo git clone https://github.com/google/ngx_brotli.git
cd ngx_brotli
sudo git submodule update --init

然后重新编译NGINX:

# 获取当前NGINX配置参数
nginx -V

# 使用相同参数加上Brotli模块重新编译
cd /usr/src
sudo wget http://nginx.org/download/nginx-$(nginx -v 2>&1 | awk -F'/' '{print $2}').tar.gz
sudo tar zxvf nginx-*.tar.gz
cd nginx-*
sudo ./configure [原有参数] --add-module=/usr/src/ngx_brotli
sudo make
sudo make install

在NGINX配置中添加:

brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

4.2 启用HTTP/3 (QUIC)

# 安装依赖
sudo apt install -y mercurial cmake golang

# 编译支持HTTP/3的NGINX
cd /usr/src
sudo hg clone -b quic https://hg.nginx.org/nginx-quic
cd nginx-quic

# 下载并编译BoringSSL
sudo mkdir -p boringssl && cd boringssl
sudo wget https://boringssl.googlesource.com/boringssl/+archive/master.tar.gz
sudo tar zxvf master.tar.gz
sudo mkdir build && cd build
sudo cmake ..
sudo make
cd ../..

# 配置NGINX
sudo ./auto/configure --prefix=/etc/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=/var/run/nginx.pid \
                      --lock-path=/var/run/nginx.lock \
                      --http-client-body-temp-path=/var/cache/nginx/client_temp \
                      --http-proxy-temp-path=/var/cache/nginx/proxy_temp \
                      --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
                      --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
                      --http-scgi-temp-path=/var/cache/nginx/scgi_temp \
                      --user=nginx \
                      --group=nginx \
                      --with-compat \
                      --with-file-aio \
                      --with-threads \
                      --with-http_addition_module \
                      --with-http_auth_request_module \
                      --with-http_dav_module \
                      --with-http_flv_module \
                      --with-http_gunzip_module \
                      --with-http_gzip_static_module \
                      --with-http_mp4_module \
                      --with-http_random_index_module \
                      --with-http_realip_module \
                      --with-http_secure_link_module \
                      --with-http_slice_module \
                      --with-http_ssl_module \
                      --with-http_stub_status_module \
                      --with-http_sub_module \
                      --with-http_v2_module \
                      --with-mail \
                      --with-mail_ssl_module \
                      --with-stream \
                      --with-stream_realip_module \
                      --with-stream_ssl_module \
                      --with-stream_ssl_preread_module \
                      --with-cc-opt='-I../boringssl/include -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' \
                      --with-ld-opt='-L../boringssl/build/ssl -L../boringssl/build/crypto'

sudo make
sudo make install

在NGINX配置中添加:

server {
    listen 443 quic reuseport;
    listen [::]:443 quic reuseport;

    # 添加HTTP/3支持头
    add_header Alt-Svc 'h3=":443"; ma=86400, h3-29=":443"; ma=86400';
}

4.3 数据库连接优化

对于Node.js应用,使用连接池优化数据库连接:

const { Pool } = require('pg'); // PostgreSQL示例

const pool = new Pool({
  user: 'dbuser',
  host: 'localhost',
  database: 'mydb',
  password: 'securepassword',
  port: 5432,
  max: 20, // 最大连接数
  idleTimeoutMillis: 30000, // 空闲连接超时
  connectionTimeoutMillis: 2000 // 连接超时
});

5. 监控与维护

5.1 安装和配置Prometheus + Grafana

# 安装Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-*
./prometheus --config.file=prometheus.yml &

# 安装Node Exporter (用于系统监控)
wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz
tar xvfz node_exporter-*
cd node_exporter-*
./node_exporter &

# 安装Grafana
sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana_9.1.5_amd64.deb
sudo dpkg -i grafana_*.deb
sudo systemctl start grafana-server

5.2 PM2监控仪表板

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

# 访问监控界面
pm2 plus

6. 安全加固

6.1 防火墙配置

# 安装UFW
sudo apt install -y ufw

# 基本规则
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable

6.2 Fail2Ban安装

sudo apt install -y fail2ban

# 创建本地配置
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# 编辑配置
sudo nano /etc/fail2ban/jail.local

添加以下内容:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 3
bantime = 86400

重启服务:

sudo systemctl restart fail2ban

7. 备份策略

7.1 自动化备份脚本

创建 /usr/local/bin/backup_server.sh:

```bash

!/bin/bash

备份目录

BACKUP_DIR="/backups" DATE=$(date +%Y-%m-%d_%H-%M-%S)

创建备份目录

mkdir -p $BACKUP_DIR/$DATE

备份NGINX配置

tar -czvf $BACKUP_DIR/$DATE/nginx_conf.tar.gz /etc/nginx

备份网站数据

tar -czvf $BACKUP_DIR/$DATE/websites.tar.gz /var/www

备份数据库 (MySQL示例)

mysqldump -u root -p'yourpassword' --all-databases > $BACKUP_DIR/$DATE/all_databases.sql

备份PM2配置

pm2 save tar -czvf $BACKUP_DIR/$DATE/pm2_config.tar.gz ~/.pm2

保留最近7天的备份

find $BACKUP_DIR/* -