在腾讯云轻量应用服务器(Lighthouse)上部署 Node.js 接口,是一个非常常见且实用的操作。下面是一步一步的详细指南,帮助你完成从购买服务器到部署 Node.js 后端接口的全过程。
✅ 一、准备工作
-
购买腾讯云轻量应用服务器
- 登录 腾讯云控制台
- 进入「轻量应用服务器 Lighthouse」
- 创建实例:
- 地域:选择离用户近的(如广州、上海)
- 镜像:选择
Ubuntu Server 20.04 LTS或CentOS 7.x - 套餐:1核2G起步即可(适合测试/小项目)
- 设置登录密码或密钥对
-
获取公网 IP 和 SSH 登录信息
✅ 二、连接服务器(SSH)
使用终端(Mac/Linux)或工具如 PuTTY / Xshell / FinalShell(Windows):
ssh root@你的公网IP
# 输入密码登录
✅ 三、安装必要环境
1. 更新系统包
# Ubuntu
sudo apt update && sudo apt upgrade -y
# CentOS
sudo yum update -y
2. 安装 Node.js(推荐使用 nvm)
# 安装 nvm(Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 重新加载配置
source ~/.bashrc
# 安装 Node.js(例如 v18)
nvm install 18
# 检查是否成功
node -v # 应输出 v18.x.x
npm -v
📌 建议使用长期支持版本(LTS),如 Node.js 18 或 20。
3. 安装 PM2(进程管理器,用于后台运行)
npm install -g pm2
✅ 四、上传并部署 Node.js 项目
方法一:直接在服务器上拉取代码(推荐使用 Git)
- 在服务器上克隆你的项目(确保你已将代码推送到 GitHub/Gitee)
git clone https://github.com/你的用户名/你的node项目.git
cd 你的node项目
- 安装依赖
npm install
- 启动项目(测试)
node app.js # 或 npm start
确保你的入口文件(如
app.js或server.js)监听的是0.0.0.0而不是localhost,否则外部无法访问。
示例:
app.listen(3000, '0.0.0.0', () => {
console.log('Server running on port 3000');
});
方法二:本地打包上传(使用 SCP 或 FTP 工具)
# 本地终端执行(非服务器)
scp -r ./your-node-project root@你的IP:/root/
然后在服务器进入目录安装依赖。
✅ 五、使用 PM2 启动并守护进程
pm2 start app.js --name "my-api"
# 查看运行状态
pm2 list
# 查看日志
pm2 logs my-api
设置开机自启:
pm2 startup
# 按提示执行生成的命令,例如:
# pm2 save
✅ 六、配置防火墙和安全组
-
腾讯云控制台设置安全组
- 进入轻量服务器详情页 → 防火墙
- 添加规则:
- 协议类型:TCP
- 端口:
3000(或你 Node 服务用的端口) - 源 IP:
0.0.0.0/0(或限制为特定 IP)
-
服务器本地防火墙(可选)
# Ubuntu 使用 ufw
sudo ufw allow 3000
# CentOS 使用 firewalld
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
✅ 七、通过域名访问(可选)
- 备案域名并解析到服务器公网 IP
- 使用 Nginx 反向X_X(推荐)
安装 Nginx
# Ubuntu
sudo apt install nginx -y
# CentOS
sudo yum install nginx -y
启动并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
配置反向X_X
编辑配置文件:
sudo nano /etc/nginx/sites-available/default
添加:
server {
listen 80;
server_name yourdomain.com; # 替换为你的域名或IP
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;
}
}
测试配置并重启 Nginx:
sudo nginx -t
sudo systemctl restart nginx
现在可以通过 http://yourdomain.com 访问你的 Node 接口。
✅ 八、其他建议
- 使用
.env文件管理环境变量(如数据库连接) - 使用
pm2 ecosystem.config.js管理多项目 - 开启 HTTPS(使用 Let's Encrypt + Certbot)
- 定期备份数据和代码
✅ 总结流程图
购买服务器 → SSH 登录 → 安装 Node + PM2 → 上传代码 → 安装依赖 → PM2 启动 → 配置防火墙 → 域名/Nginx → 对外访问
如果你提供具体的项目结构(如 Express/Koa/Fastify),我可以给出更精确的部署命令和配置。
需要我帮你写一个 ecosystem.config.js 或 Nginx 配置模板吗?
CLOUD云计算