在单核 2GB 内存的服务器上部署小程序后端(Node.js + Nginx)需要非常谨慎的资源管理,因为 Node.js 是单线程模型且内存占用较高。以下是经过验证的最佳实践方案:
一、核心架构设计
用户请求 → Nginx (静态资源/反向X_X) → PM2 (Node.js进程管理) → Node.js应用
二、Nginx 配置优化
1. 基础配置 (/etc/nginx/nginx.conf)
user www-data;
worker_processes 1; # 单核服务器设为1
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 1024; # 适当降低连接数
use epoll; # Linux专用事件模型
}
http {
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"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript
text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 1000;
# 上传大小限制
client_max_body_size 10m;
include /etc/nginx/conf.d/*.conf;
}
2. 站点配置 (/etc/nginx/conf.d/default.conf)
server {
listen 80;
server_name your-domain.com;
# 静态文件服务
location /static/ {
root /var/www/html;
expires 30d;
add_header Cache-Control "public, immutable";
}
# API反向X_X
location /api/ {
proxy_pass http://127.0.0.1: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_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲设置
proxy_buffering off;
proxy_request_buffering off;
}
# WebSocket支持(如果需要)
location /ws/ {
proxy_pass http://127.0.0.1:3000/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 86400s;
}
# 健康检查端点
location /health {
return 200 'OK';
add_header Content-Type text/plain;
}
# 错误页面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
三、Node.js 应用优化
1. 使用 PM2 进程管理器
安装 PM2:
npm install -g pm2
创建 ecosystem.config.js:
module.exports = {
apps: [{
name: 'miniprogram-api',
script: './app.js',
instances: 1, // 单核只启动1个实例
exec_mode: 'fork', // 不使用cluster模式
// 内存限制
max_memory_restart: '350M', // 触发重启的内存阈值
// 日志配置
log_date_format: 'YYYY-MM-DD HH:mm:ss',
merge_logs: true,
// 环境变量
env_production: {
NODE_ENV: 'production',
PORT: 3000
},
// 自动重启策略
autorestart: true,
watch: false,
ignore_watch: ['node_modules', 'logs'],
// 优雅关闭
kill_timeout: 5000,
listen_timeout: 3000
}]
};
启动应用:
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup systemd # 设置开机自启
2. Node.js 代码优化
// app.js - 最小化依赖和内存泄漏
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const app = express();
// 安全中间件
app.use(helmet({
contentSecurityPolicy: false, // 小程序可能不需要CSP
crossOriginEmbedderPolicy: false
}));
// 压缩响应
app.use(compression({
threshold: 1024, // 小于1KB的不压缩
level: 6 // 平衡压缩率和CPU使用
}));
// 速率限制
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 每个IP最多100次请求
standardHeaders: true,
legacyHeaders: false
});
app.use(limiter);
// 请求体解析限制
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));
// 数据库连接池优化(以MySQL为例)
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10, // 根据内存调整
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 0
});
// 缓存层(Redis轻量级缓存)
let redisClient = null;
try {
const Redis = require('ioredis');
redisClient = new Redis({
host: process.env.REDIS_HOST || '127.0.0.1',
port: 6379,
maxRetriesPerRequest: 3,
lazyConnect: true
});
} catch (e) {
console.warn('Redis unavailable, using memory cache');
}
// 简单内存缓存
const memoryCache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5分钟
function getFromCache(key) {
const cached = memoryCache.get(key);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
memoryCache.delete(key);
return null;
}
function setToCache(key, data) {
memoryCache.set(key, {
data,
timestamp: Date.now()
});
// 清理过期缓存
if (memoryCache.size > 100) {
const oldestKey = memoryCache.keys().next().value;
memoryCache.delete(oldestKey);
}
}
// API路由示例
app.get('/api/user/:id', async (req, res) => {
try {
const cacheKey = `user_${req.params.id}`;
const cached = getFromCache(cacheKey);
if (cached) {
return res.json(cached);
}
// 查询数据库
const [rows] = await pool.query(
'SELECT id, nickname, avatar FROM users WHERE id = ?',
[req.params.id]
);
if (!rows.length) {
return res.status(404).json({ error: 'User not found' });
}
const userData = rows[0];
setToCache(cacheKey, userData);
res.json(userData);
} catch (error) {
console.error('Database error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// 错误处理
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// 优雅关闭
process.on('SIGTERM', async () => {
console.log('SIGTERM received, shutting down gracefully');
await pool.end();
if (redisClient) {
await redisClient.quit();
}
process.exit(0);
});
四、系统级优化
1. Linux 内核参数优化 (/etc/sysctl.conf)
# TCP连接优化
net.core.somaxconn = 1024
net.ipv4.tcp_max_syn_backlog = 1024
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
# 内存优化
vm.swappiness = 10 # 减少swap使用
vm.vfs_cache_pressure = 50
应用配置:
sysctl -p
2. 监控和告警
安装简单的监控工具:
# 安装htop监控
apt install htop
# 创建监控脚本
cat > /usr/local/bin/check-server.sh << 'EOF'
#!/bin/bash
MEMORY=$(free -m | awk '/MemAvailable:/ {print $2}')
CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
if [ "$MEMORY" -lt 200 ]; then
echo "Low memory: ${MEMORY}MB available" | mail -s "Server Alert" admin@example.com
fi
if [ "$CPU" -gt 80 ]; then
echo "High CPU: ${CPU}%" | mail -s "Server Alert" admin@example.com
fi
EOF
chmod +x /usr/local/bin/check-server.sh
# 添加cron任务
echo "*/5 * * * * /usr/local/bin/check-server.sh" >> /etc/crontab
3. 日志轮转
# 安装logrotate
apt install logrotate
# 创建配置
cat > /etc/logrotate.d/nodejs << 'EOF'
/var/log/pm2/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0644 www-data www-data
}
EOF
五、部署流程
1. Docker 容器化部署(推荐)
# Dockerfile
FROM node:18-alpine
WORKDIR /app
# 安装依赖
COPY package*.json ./
RUN npm ci --only=production
# 复制应用代码
COPY . .
# 创建非root用户
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
EXPOSE 3000
CMD ["pm2", "start", "ecosystem.config.js", "--env", "production"]
构建和运行:
docker build -t miniprogram-api .
docker run -d
--name miniprogram-api
--restart unless-stopped
-p 3000:3000
-e NODE_ENV=production
-e DB_HOST=db-host
-e REDIS_HOST=redis-host
miniprogram-api
2. 传统部署方式
# 克隆代码
git clone https://github.com/your-repo/miniprogram-backend.git
cd miniprogram-backend
# 安装依赖
npm ci --only=production
# 创建生产环境配置文件
cp .env.example .env.production
# 编辑 .env.production 填入实际配置
# 启动PM2
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup
六、性能调优建议
1. 数据库优化
- 使用索引覆盖常用查询
- 启用查询缓存
- 定期清理慢查询日志
- 考虑使用读写分离
2. 缓存策略
- LRU缓存热点数据
- 设置合理的TTL
- 使用布隆过滤器防止缓存穿透
3. 代码优化
- 避免全局变量存储大量数据
- 使用流式处理大文件
- 异步处理I/O操作
- 定期GC触发(谨慎使用)
4. 监控指标
// 添加自定义监控
const os = require('os');
setInterval(() => {
const memUsage = process.memoryUsage();
const cpuUsage = os.loadavg()[0];
console.log(`Memory: RSS=${memUsage.rss/1024/1024}MB, Heap=${memUsage.heapUsed/1024/1024}MB`);
console.log(`CPU Load: ${cpuUsage}%`);
}, 60000); // 每分钟记录一次
七、故障排除清单
- 内存溢出:检查是否有内存泄漏,使用
--inspect调试 - CPU过高:分析热点函数,优化算法复杂度
- 连接超时:调整Nginx和Node.js的超时设置
- 磁盘空间不足:定期清理日志和临时文件
- 网络问题:检查防火墙规则和网络带宽
这套方案在单核2G环境下应该能够稳定运行,预计可支撑日均1-5万PV的小程序后端服务。关键是要持续监控资源使用情况,并根据实际需求进行微调。
轻量云Cloud