工作进程配置:
worker_processes auto; # 自动匹配CPU核心数
worker_rlimit_nofile 100000; # 每个worker能打开的文件描述符数量
事件模块优化:
events {
worker_connections 4096; # 每个worker的最大连接数
multi_accept on; # 一次接受所有新连接
use epoll; # Linux下高性能事件模型
}
HTTP基础优化:
http {
sendfile on; # 启用高效文件传输
tcp_nopush on; # 仅在sendfile开启时有效,优化数据包发送
tcp_nodelay on; # 禁用Nagle算法,减少延迟
keepalive_timeout 30; # 保持连接超时时间
keepalive_requests 1000; # 单个连接最大请求数
types_hash_max_size 2048;
server_tokens off; # 隐藏NGINX版本信息
}
server {
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
access_log off;
}
}
gzip on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /api/ {
limit_req zone=one burst=20 nodelay;
}
}
安装PM2:
npm install pm2 -g
启动应用:
pm2 start app.js -i max --name "myapp"
-i max
:根据CPU核心数启动最大实例数--name
:为应用命名集群模式:
pm2 start app.js -i 4 --name "myapp" # 手动指定4个实例
内存限制:
pm2 start app.js --max-memory-restart 300M
日志管理:
pm2 logs --lines 200 # 查看最近200行日志
pm2 flush # 清空日志
创建ecosystem.config.js
:
module.exports = {
apps: [{
name: 'myapp',
script: 'app.js',
instances: 'max',
exec_mode: 'cluster',
max_memory_restart: '300M',
env: {
NODE_ENV: 'production'
},
merge_logs: true,
log_date_format: 'YYYY-MM-DD HH:mm Z',
error_file: '/var/log/myapp/err.log',
out_file: '/var/log/myapp/out.log'
}]
}
内核参数调优:
# /etc/sysctl.conf
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000
net.core.somaxconn = 65535
文件描述符限制:
# /etc/security/limits.conf
* soft nofile 100000
* hard nofile 100000
NGINX状态监控:
server {
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
PM2监控:
pm2 monit # 实时监控
pm2 list # 查看应用列表
pm2 show <app_name> # 查看应用详情
日志轮转:
安装logrotate
并配置定期轮转NGINX和PM2日志。
NGINX安全:
server {
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self'";
}
PM2安全:
pm2 startup # 设置PM2开机启动
pm2 save # 保存当前进程列表
通过以上配置,您的VPS服务器将获得显著的网络性能提升,同时保持稳定性和安全性。根据实际负载情况,可能需要进一步调整参数以达到最佳效果。