阿里云 CentOS 服务器部署微信小程序 Node.js 后端完整教程
一、前期准备
1. 硬件与环境要求
- 阿里云 ECS 实例:CentOS 7/8 或 Alibaba Cloud Linux(推荐)
- 最小配置:2核4G内存,50G系统盘+数据盘
- 安全组规则:开放端口
80、443、22(SSH)、以及你的应用端口(如3000)
2. 注册与获取资源
- 登录 阿里云控制台
- 创建 ECS 实例 → 选择 CentOS 镜像
- 设置 root 密码或 SSH 密钥对
- 配置安全组放行所需端口
二、服务器基础配置
1. 连接服务器
# 使用 SSH 连接
ssh root@<你的公网IP>
# 首次登录建议修改默认密码
passwd
2. 更新系统与安装基础工具
# CentOS 7
yum update -y
yum install -y vim git curl wget net-tools
# CentOS 8 / Alibaba Cloud Linux
dnf update -y
dnf install -y vim git curl wget net-tools
3. 配置防火墙
# 开启 firewalld
systemctl start firewalld
systemctl enable firewalld
# 开放必要端口
firewall-cmd --permanent --add-port=22/tcp # SSH
firewall-cmd --permanent --add-port=80/tcp # HTTP
firewall-cmd --permanent --add-port=443/tcp # HTTPS
firewall-cmd --permanent --add-port=3000/tcp # Node.js 应用(根据实际端口调整)
# 重载防火墙
firewall-cmd --reload
三、安装 Node.js 和 NPM
方法一:使用 nvm(推荐,便于版本管理)
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 使配置生效
source ~/.bashrc
# 安装指定版本的 Node.js(推荐 LTS 版本)
nvm install 18
nvm use 18
nvm alias default 18
# 验证安装
node -v
npm -v
方法二:直接安装 NodeSource
# 添加 NodeSource 仓库
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
# 安装 Node.js
yum install -y nodejs
# 验证
node -v
npm -v
四、安装数据库(以 MySQL 为例)
1. 安装 MySQL
# CentOS 7
yum install -y mysql-server
systemctl start mysqld
systemctl enable mysqld
# 初始化 root 密码
mysql_secure_installation
2. 创建数据库和用户
-- 登录 MySQL
mysql -u root -p
-- 创建数据库
CREATE DATABASE wx_app_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建用户并授权
CREATE USER 'wx_user'@'%' IDENTIFIED BY 'YourStrongPassword123!';
GRANT ALL PRIVILEGES ON wx_app_db.* TO 'wx_user'@'%';
FLUSH PRIVILEGES;
EXIT;
替代方案:也可使用 MongoDB、PostgreSQL 或 Redis,根据项目需求选择。
五、安装 PM2(进程管理器)
npm install -g pm2
# 验证
pm2 -v
PM2 用于:
- 后台运行 Node.js 应用
- 自动重启(崩溃后恢复)
- 日志管理
- 进程监控
六、部署 Node.js 后端代码
1. 上传代码到服务器
方式一:Git 拉取(推荐)
# 创建项目目录
mkdir -p /opt/wx-backend
cd /opt/wx-backend
# 克隆代码
git clone <你的Git仓库地址> .
# 如果仓库私有,先配置 SSH Key 或 Token
git config --global user.name "yourname"
git config --global user.email "you@email.com"
方式二:SCP 上传
# 在本地电脑执行
scp -r ./your-project/* root@<公网IP>:/opt/wx-backend/
2. 安装项目依赖
cd /opt/wx-backend
npm install --production
3. 配置环境变量
# 创建 .env 文件
cat > /opt/wx-backend/.env << EOF
NODE_ENV=production
PORT=3000
DB_HOST=localhost
DB_PORT=3306
DB_NAME=wx_app_db
DB_USER=wx_user
DB_PASSWORD=YourStrongPassword123!
JWT_SECRET=your_jwt_secret_key_change_this
WX_APPID=your_wechat_appid
WX_SECRET=your_wechat_secret
EOF
4. 测试启动
# 临时启动测试
node server.js
# 或
npm start
# 访问测试
curl http://localhost:3000/api/health
七、使用 PM2 守护进程
1. 启动应用
cd /opt/wx-backend
pm2 start server.js --name "wx-backend"
2. 常用 PM2 命令
# 查看状态
pm2 list
# 查看日志
pm2 logs wx-backend
# 实时监控
pm2 monit
# 停止
pm2 stop wx-backend
# 重启
pm2 restart wx-backend
# 删除进程
pm2 delete wx-backend
3. 设置开机自启
# 生成启动脚本
pm2 startup systemd
# 保存当前进程列表
pm2 save
# 验证自启
systemctl status pm2-root
八、配置 Nginx 反向X_X + SSL 证书
1. 安装 Nginx
yum install -y nginx
systemctl start nginx
systemctl enable nginx
2. 申请 SSL 证书
方式一:免费 Let’s Encrypt(Certbot)
# 安装 Certbot
yum install -y certbot python3-certbot-nginx
# 申请证书(需域名已解析到服务器 IP)
certbot --nginx -d yourdomain.com
# 自动续期测试
certbot renew --dry-run
方式二:阿里云免费 SSL 证书
- 登录 SSL 证书控制台
- 购买/申请免费证书
- 下载 Nginx 格式的证书文件
- 上传到服务器
/etc/nginx/ssl/目录
3. 配置 Nginx
# 备份默认配置
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
# 创建站点配置
cat > /etc/nginx/conf.d/wx-backend.conf << 'EOF'
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# HTTP 强制跳转 HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
# SSL 证书路径(Let's Encrypt)
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# SSL 优化配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
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 / {
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_cache_bypass $http_upgrade;
}
# 限制请求大小
client_max_body_size 10m;
# 日志
access_log /var/log/nginx/wx-backend-access.log;
error_log /var/log/nginx/wx-backend-error.log warn;
}
EOF
4. 测试并重载 Nginx
# 测试配置文件语法
nginx -t
# 重载 Nginx
systemctl reload nginx
# 确保 Nginx 开机自启
systemctl enable nginx
九、微信小程序配置
1. 配置服务器域名
- 登录 微信公众平台
- 进入 开发 → 开发设置 → 服务器域名
- 添加 request 合法域名:
https://yourdomain.com - 添加 socket 合法域名(如使用 WebSocket):
wss://yourdomain.com
2. 小程序端调用示例
// pages/index/index.js
Page({
onLoad() {
this.getUserInfo();
},
getUserInfo() {
wx.login({
success: (res) => {
const code = res.code;
wx.request({
url: 'https://yourdomain.com/api/login',
method: 'POST',
data: { code: code },
header: {
'Content-Type': 'application/json'
},
success: (response) => {
console.log('登录成功:', response.data);
// 保存 token
wx.setStorageSync('token', response.data.token);
},
fail: (err) => {
console.error('请求失败:', err);
}
});
}
});
}
});
十、安全加固
1. 禁用 root SSH 密码登录,改用密钥
# 编辑 SSH 配置
vim /etc/ssh/sshd_config
# 修改以下项:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
# 重启 SSH
systemctl restart sshd
2. 安装 Fail2Ban 防暴力破解
yum install -y epel-release
yum install -y fail2ban
systemctl start fail2ban
systemctl enable fail2ban
3. 定期更新系统
# 创建自动更新脚本
cat > /usr/local/bin/auto-update << 'EOF'
#!/bin/bash
yum update -y && reboot
EOF
chmod +x /usr/local/bin/auto-update
# 添加到 crontab(每周日凌晨3点)
crontab -e
0 3 * * 0 /usr/local/bin/auto-update >> /var/log/system-update.log 2>&1
4. 数据库安全
-- 限制远程访问
ALTER USER 'wx_user'@'%' IDENTIFIED WITH mysql_native_password BY 'StrongPassword!';
-- 或者只允许 localhost 连接
DROP USER 'wx_user'@'%';
CREATE USER 'wx_user'@'localhost' IDENTIFIED BY 'StrongPassword!';
GRANT ALL PRIVILEGES ON wx_app_db.* TO 'wx_user'@'localhost';
FLUSH PRIVILEGES;
十一、监控与维护
1. 系统监控
# 查看 CPU/内存
top
# 查看磁盘使用
df -h
# 查看日志
tail -f /var/log/messages
tail -f /var/log/nginx/wx-backend-error.log
# PM2 监控
pm2 monit
2. 日志轮转配置
# PM2 日志已自动管理,如需自定义可配置 logrotate
cat > /etc/logrotate.d/nginx << 'EOF'
/var/log/nginx/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
systemctl reload nginx
endscript
}
EOF
3. 备份策略
# 数据库备份脚本
cat > /usr/local/bin/db-backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/opt/backups/db"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
mysqldump -u root -p'YourRootPassword' wx_app_db > $BACKUP_DIR/wx_app_$DATE.sql
gzip $BACKUP_DIR/wx_app_$DATE.sql
# 保留最近7天备份
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
EOF
chmod +x /usr/local/bin/db-backup.sh
# 每天凌晨2点备份
crontab -e
0 2 * * * /usr/local/bin/db-backup.sh >> /var/log/db-backup.log 2>&1
十二、常见问题排查
| 问题 | 解决方案 |
|---|---|
ECONNREFUSED |
检查 PM2 进程是否运行:pm2 list;检查端口是否被占用:netstat -tlnp |
| CORS 错误 | 在后端启用 CORS:app.use(cors());或在 Nginx 中添加 Access-Control-Allow-Origin |
| 502 Bad Gateway | Nginx 无法连接到上游服务;检查 proxy_pass 地址和端口是否正确 |
| SSL 握手失败 | 确保证书路径正确且未过期;检查 ssl_protocols 配置 |
| 微信 request 失败 | 确认已在公众平台配置了 request 合法域名;检查域名是否为 HTTPS |
| 内存泄漏 | 使用 pm2 monit 观察内存趋势;检查代码中是否有未释放的资源 |
十三、项目结构参考
/opt/wx-backend/
├── .env # 环境变量
├── package.json
├── server.js # 入口文件
├── src/
│ ├── controllers/ # 控制器
│ ├── models/ # 数据模型
│ ├── routes/ # 路由
│ ├── middleware/ # 中间件(认证、校验等)
│ └── utils/ # 工具函数
├── uploads/ # 上传文件目录
└── logs/ # 应用日志
快速一键部署脚本(可选)
#!/bin/bash
# deploy.sh - 一键部署脚本
set -e
PROJECT_DIR="/opt/wx-backend"
DOMAIN="yourdomain.com"
echo "=== 开始部署 ==="
# 1. 拉取最新代码
cd $PROJECT_DIR
git pull origin main
# 2. 安装依赖
npm install --production
# 3. 重启 PM2
pm2 restart wx-backend || pm2 start server.js --name "wx-backend"
# 4. 重载 Nginx
nginx -t && systemctl reload nginx
echo "=== 部署完成 ==="
pm2 status
总结:整个部署流程为 服务器准备 → 环境安装 → 代码部署 → 进程管理 → 反向X_X+SSL → 小程序对接 → 安全加固 → 监控维护。按照此步骤操作,即可稳定地将微信小程序后端部署到阿里云 CentOS 服务器上。
云知识CLOUD