在轻量应用服务器(如腾讯云轻量应用服务器、阿里云轻量服务器等)上部署 Node.js 服务供小程序调用,是常见的前后端分离开发方式。以下是完整的部署流程和注意事项:
✅ 一、准备工作
1. 购买并配置轻量应用服务器
- 登录云服务商控制台(如腾讯云、阿里云)。
- 购买轻量应用服务器(推荐选择 Ubuntu/CentOS 系统)。
- 开放以下端口:
- 22:SSH 远程登录
- 80/443:HTTP/HTTPS 访问
- 自定义端口(如
3000、5000):Node.js 服务运行端口
- 获取公网 IP 地址。
⚠️ 注意:小程序要求后端接口必须使用 HTTPS 协议,因此建议后续配置 Nginx + SSL 证书实现 HTTPS。
✅ 二、连接服务器并安装环境
1. 使用 SSH 登录服务器
ssh root@你的服务器公网IP
2. 安装 Node.js 和 npm
推荐使用 nvm(Node Version Manager)管理版本:
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 重新加载 shell 配置
source ~/.bashrc
# 安装 Node.js(推荐 LTS 版本)
nvm install 18
nvm use 18
验证安装:
node -v # 应输出 v18.x.x
npm -v
✅ 三、上传并部署 Node.js 项目
1. 上传代码到服务器
方法一:使用 Git
git clone https://github.com/yourname/your-node-project.git
cd your-node-project
npm install
方法二:使用 SCP 上传本地文件
scp -r ./your-project root@your-server-ip:/root/
2. 启动 Node.js 服务(测试)
node app.js # 或 server.js、index.js 等主文件
假设你的服务监听
http://localhost:3000/api/login
✅ 四、使用 PM2 持久化运行 Node.js 服务
避免进程退出或断开 SSH 后服务停止。
1. 安装 PM2
npm install -g pm2
2. 启动服务
pm2 start app.js --name "my-api"
3. 设置开机自启
pm2 startup
pm2 save
4. 查看状态
pm2 list
pm2 logs my-api
✅ 五、配置 Nginx 反向X_X(支持 HTTPS)
1. 安装 Nginx
apt update
apt install nginx -y
systemctl start nginx
systemctl enable nginx
2. 配置反向X_X
编辑配置文件:
nano /etc/nginx/sites-available/default
添加如下配置(假设 Node.js 监听 3000 端口):
server {
listen 80;
server_name your-domain.com; # 替换为你的域名
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;
}
}
3. 测试并重载 Nginx
nginx -t
systemctl reload nginx
✅ 六、申请 SSL 证书(HTTPS 必须)
推荐使用 Let’s Encrypt(免费)
1. 安装 Certbot
apt install certbot python3-certbot-nginx -y
2. 申请并配置 HTTPS
certbot --nginx -d your-domain.com
按提示操作,Certbot 会自动修改 Nginx 配置并启用 HTTPS。
✅ 此时访问
https://your-domain.com即可安全访问你的 API。
✅ 七、小程序中调用接口
1. 在小程序 app.json 中配置 request 合法域名
{
"request": {
"header": {
"content-type": "application/json"
},
"timeout": 60000,
"url": "https://your-domain.com"
}
}
2. 发起请求示例(微信小程序)
wx.request({
url: 'https://your-domain.com/api/login',
method: 'POST',
data: {
code: 'xxx'
},
success(res) {
console.log(res.data);
}
})
✅ 八、安全与优化建议
| 项目 | 建议 |
|---|---|
| 🔐 域名 | 使用备案域名,不能使用 IP 直接调用(小程序限制) |
| 🔒 HTTPS | 必须使用 HTTPS,否则小程序无法请求 |
| 🛡️ 防火墙 | 开放 80/443,关闭非必要端口 |
| 📊 日志监控 | 使用 pm2 logs 查看错误 |
| 🔄 自动部署 | 可结合 GitHub Actions 或 webhook 实现自动更新 |
✅ 总结步骤
- 购买轻量服务器 → 2. 安装 Node.js → 3. 上传代码
→ 4. PM2 启动服务 → 5. Nginx 反向X_X → 6. SSL 配置 HTTPS
→ 7. 小程序调用https://your-domain.com/api/xxx
如有具体框架(如 Express、Koa、NestJS),可进一步提供代码结构帮你定制部署脚本。
需要我为你生成一个完整的 Express + Nginx + HTTPS 部署脚本吗?
云知识