阿里云 CentOS 服务器部署微信小程序 Node.js 后端完整教程
一、前期准备
1. 所需材料
- 阿里云 ECS 云服务器(CentOS 7/8)
- 已备案的域名 + SSL 证书(小程序要求 HTTPS)
- 微信开发者工具
- Node.js 项目代码
2. 购买并配置阿里云 ECS
步骤:
1. 登录阿里云控制台 → 创建 ECS 实例
2. 选择操作系统:CentOS 7.9 或 CentOS 8
3. 安全组规则开放端口:
- 22 (SSH)
- 80 (HTTP)
- 443 (HTTPS)
- 你的应用端口,如 3000
4. 绑定弹性 IP 和域名
5. 上传 SSL 证书到服务器
二、服务器环境搭建
1. SSH 连接服务器
ssh root@your_server_ip
2. 更新系统
# CentOS 7
yum update -y
# CentOS 8
dnf update -y
3. 安装 Nginx
# CentOS 7
yum install nginx -y
systemctl start nginx
systemctl enable nginx
# CentOS 8
dnf install nginx -y
systemctl start nginx
systemctl enable nginx
4. 安装 Node.js(推荐 nvm 管理多版本)
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 重新加载 shell
source ~/.bashrc
# 安装 Node.js LTS 版本
nvm install --lts
# 验证
node -v
npm -v
5. 安装 PM2(进程管理器)
npm install -g pm2
pm2 --version
6. 安装 MySQL(可选,根据需求)
# CentOS 7
yum install mysql-server -y
systemctl start mysqld
systemctl enable mysqld
# 设置 root 密码
mysql_secure_installation
7. 安装 Redis(可选,用于缓存)
yum install redis -y
systemctl start redis
systemctl enable redis
三、部署 Node.js 后端项目
1. 将项目上传到服务器
# 方式一:使用 scp
scp -r ./your_project root@your_server_ip:/root/your_project
# 方式二:使用 git clone
git clone https://github.com/your-repo/your-project.git /root/your_project
# 方式三:使用 rsync
rsync -avz ./your_project/ root@your_server_ip:/root/your_project/
2. 进入项目目录并安装依赖
cd /root/your_project
npm install --production
3. 配置环境变量
# 创建 .env 文件
cat > .env << EOF
PORT=3000
NODE_ENV=production
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=your_db
JWT_SECRET=your_secret_key
REDIS_HOST=localhost
REDIS_PORT=6379
EOF
4. 用 PM2 启动应用
# 启动应用
pm2 start app.js --name "wechat-backend"
# 或者使用 ecosystem 配置文件
pm2 start ecosystem.config.js
# 查看状态
pm2 status
# 查看日志
pm2 logs wechat-backend
# 设置开机自启
pm2 startup
pm2 save
5. ecosystem.config.js 示例
module.exports = {
apps: [{
name: 'wechat-backend',
script: 'app.js',
instances: 'max', // 多核并行
exec_mode: 'cluster',
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: '/var/log/pm2/wechat-backend-error.log',
out_file: '/var/log/pm2/wechat-backend-out.log',
merge_logs: true
}]
};
四、配置 Nginx 反向X_X + HTTPS
1. 获取/配置 SSL 证书
# 在阿里云控制台下载 SSL 证书
# 上传到服务器
mkdir -p /etc/nginx/ssl
scp your_cert.pem root@your_server_ip:/etc/nginx/ssl/cert.pem
scp your_key.pem root@your_server_ip:/etc/nginx/ssl/key.pem
2. 配置 Nginx
vim /etc/nginx/conf.d/wechat.conf
# HTTP 强制跳转 HTTPS
server {
listen 80;
server_name your_domain.com www.your_domain.com;
return 301 https://$host$request_uri;
}
# HTTPS 配置
server {
listen 443 ssl http2;
server_name your_domain.com www.your_domain.com;
# SSL 证书配置
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
# 推荐使用更安全的协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers on;
# 静态资源缓存
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# API 反向X_X
location /api/ {
proxy_pass http://127.0.0.1:3000/api/;
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;
# 超时设置(小程序请求可能较长)
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# 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 86400;
}
# 健康检查接口
location /health {
access_log off;
return 200 '{"status":"ok"}';
add_header Content-Type application/json;
}
}
3. 测试并重启 Nginx
# 测试配置语法
nginx -t
# 如果通过,重载 Nginx
nginx -s reload
# 或重启
systemctl restart nginx
systemctl enable nginx
五、微信小程序配置
1. 登录微信公众平台
- 进入 开发管理 → 开发设置
- 添加服务器域名:
https://your_domain.com - 确保域名已备案且指向你的服务器 IP
2. 小程序端请求示例
// wx.request 调用后端 API
wx.request({
url: 'https://your_domain.com/api/user/login',
method: 'POST',
data: {
code: 'login_code_from_wx.login()'
},
header: {
'Content-Type': 'application/json'
},
success(res) {
console.log('登录成功:', res.data);
// 保存 token
wx.setStorageSync('token', res.data.token);
},
fail(err) {
console.error('请求失败:', err);
}
});
3. 后端登录接口示例(Express)
const express = require('express');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const router = express.Router();
// 微信小程序登录接口
router.post('/login', async (req, res) => {
try {
const { code } = req.body;
// 1. 调用微信接口获取 openid 和 session_key
const appId = process.env.WX_APP_ID;
const appSecret = process.env.WX_APP_SECRET;
const wxRes = await axios.get(
`https://api.weixin.qq.com/sns/jscode2session`,
{
params: {
appid: appId,
secret: appSecret,
js_code: code,
grant_type: 'authorization_code'
}
}
);
const { openid, session_key } = wxRes.data;
if (!openid) {
return res.status(400).json({
code: 400,
message: '微信登录失败'
});
}
// 2. 生成 JWT Token
const token = jwt.sign(
{ openid, userId: /* 从数据库查询 */ },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// 3. 返回 token
res.json({
code: 200,
message: '登录成功',
data: { token, openid }
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({
code: 500,
message: '服务器内部错误'
});
}
});
module.exports = router;
六、安全加固
1. 防火墙配置
# CentOS 7
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
# 只开放必要端口
firewall-cmd --list-all
2. SSH 安全加固
vim /etc/ssh/sshd_config
# 修改以下配置:
PermitRootLogin no # 禁止 root 直接登录
PasswordAuthentication yes # 建议改用密钥登录
Port 22 # 可改为非标准端口增加安全性
MaxAuthTries 3 # 限制尝试次数
systemctl restart sshd
3. 使用密钥登录 SSH
# 本地生成密钥
ssh-keygen -t rsa -b 4096
# 上传公钥到服务器
ssh-copy-id user@your_server_ip
# 禁用密码登录
vim /etc/ssh/sshd_config
PasswordAuthentication no
systemctl restart sshd
4. 安装 Fail2Ban(防暴力破解)
yum install fail2ban -y
systemctl start fail2ban
systemctl enable fail2ban
5. 定期备份
# 创建备份脚本
cat > /root/backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/root/backups"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
# 备份数据库
mysqldump -u root -p'password' your_db > $BACKUP_DIR/db_$DATE.sql
# 备份项目代码
tar -czf $BACKUP_DIR/project_$DATE.tar.gz /root/your_project
# 删除30天前的备份
find $BACKUP_DIR -type f -mtime +30 -delete
echo "Backup completed: $DATE"
EOF
chmod +x /root/backup.sh
# 设置定时任务
crontab -e
# 每天凌晨2点备份
0 2 * * * /root/backup.sh >> /var/log/backup.log 2>&1
七、监控与日志管理
1. PM2 监控
# 实时监控
pm2 monit
# 查看详细指标
pm2 show wechat-backend
2. 日志轮转(防止日志过大)
# 安装 logrotate
yum install logrotate -y
# 配置
cat > /etc/logrotate.d/pm2 << 'EOF'
/var/log/pm2/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0644 root root
}
EOF
3. 系统监控
# 安装 atop 或 htop
yum install htop -y
htop
# 磁盘空间检查
df -h
# 内存使用情况
free -h
八、常见问题排查
| 问题 | 解决方案 |
|---|---|
| 小程序无法访问 API | 检查域名是否备案、HTTPS 证书是否有效、Nginx 配置是否正确 |
| 403 Forbidden | 检查安全组规则、防火墙、Nginx 权限 |
| 502 Bad Gateway | 检查 Node.js 服务是否运行(pm2 status)、端口是否正确 |
| CORS 错误 | 在后端添加 CORS 中间件,或确保 Nginx 正确转发请求头 |
| 证书过期 | 使用 Let’s Encrypt 自动续期:certbot renew |
| 内存溢出 | 调整 PM2 max_memory_restart,优化代码,增加服务器配置 |
九、自动化部署(可选进阶)
使用 Git Hooks + CI/CD
# 服务器端配置 git hook
mkdir -p /root/your_project/.git/hooks
cat > /root/your_project/.git/hooks/post-receive << 'EOF'
#!/bin/bash
GIT_WORK_TREE=/root/your_project git checkout -f
cd /root/your_project
npm install --production
pm2 restart wechat-backend
EOF
chmod +x /root/your_project/.git/hooks/post-receive
或使用 GitHub Actions / Jenkins
# .github/workflows/deploy.yml
name: Deploy to Server
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy via SSH
uses: appleboy/scp-action@master
with:
host: ${{ secrets.SERVER_IP }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
source: "."
target: "/root/your_project"
- name: Restart PM2
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SERVER_IP }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /root/your_project
npm install --production
pm2 restart wechat-backend
十、完整架构图
微信小程序 ←HTTPS→ 阿里云 CDN/WAF ←HTTPS→ Nginx (443)
↓ 反向X_X
Node.js (PM2, 3000)
↓
MySQL / Redis / MongoDB
关键提醒:
- 小程序必须使用 HTTPS,且域名需备案
- 敏感信息(AppSecret、JWT Secret)不要硬编码,使用环境变量
- 生产环境务必关闭调试模式
- 定期更新系统和依赖包以修复安全漏洞
云服务器