Node.js项目云服务器部署全流程指南:从开发到上线
一、部署前的准备工作
1.1 云服务器选型建议
- 配置选择:根据项目类型推荐基础配置(如2核4G内存适用于中小型API服务,4核8G适合高并发应用)
- 操作系统选择:推荐Ubuntu 22.04 LTS或CentOS 8,兼顾稳定性与社区支持
- 网络配置要点:确保开放80/443端口(HTTP/HTTPS),建议配置安全组规则限制源IP
1.2 本地环境验证
在部署前需完成:
# 本地运行测试NODE_ENV=production node app.js# 压力测试示例ab -n 1000 -c 100 http://localhost:3000/
确保项目在生产模式下稳定运行,记录关键性能指标(QPS、响应时间)
二、服务器环境搭建
2.1 系统环境配置
# Ubuntu系统基础环境安装sudo apt updatesudo apt install -y nginx curl git unzip# Node.js安装(推荐使用nvm)curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bashsource ~/.bashrcnvm install --lts
2.2 数据库部署方案
- MySQL配置示例:
sudo apt install mysql-serversudo mysql_secure_installation# 安全配置后创建数据库CREATE DATABASE node_app CHARACTER SET utf8mb4;CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password';GRANT ALL PRIVILEGES ON node_app.* TO 'app_user'@'localhost';
- MongoDB部署建议:使用官方仓库安装最新稳定版,配置认证与副本集
三、项目部署实施
3.1 代码传输与版本控制
推荐使用Git进行代码管理:
# 服务器端Git仓库初始化mkdir -p ~/repos && cd ~/reposgit init --bare node-app.git# 本地推送配置git remote add production user@server_ip:~/repos/node-app.gitgit push production master
3.2 依赖管理与环境配置
# 在项目目录安装依赖cd ~/node-appnpm install --production# 环境变量配置(推荐使用dotenv)echo "DB_HOST=localhostDB_USER=app_userDB_PASS=strong_password" > .env
3.3 进程管理方案对比
| 方案 | 优点 | 缺点 |
|---|---|---|
| PM2 | 自动重启、负载均衡、日志管理 | 资源占用较高 |
| Systemd | 系统原生支持、资源控制精细 | 配置复杂 |
| Forever | 简单易用 | 功能单一 |
PM2配置示例:
// ecosystem.config.jsmodule.exports = {apps: [{name: "node-app",script: "./app.js",instances: "max",exec_mode: "cluster",env: {NODE_ENV: "production",PORT: 3000},error_file: "/var/log/node-app/error.log",out_file: "/var/log/node-app/out.log"}]};
四、安全加固措施
4.1 防火墙配置
# Ubuntu ufw配置示例sudo ufw allow 22/tcp # SSHsudo ufw allow 80/tcp # HTTPsudo ufw allow 443/tcp # HTTPSsudo ufw enable
4.2 SSL证书配置(Let’s Encrypt)
# 安装Certbotsudo apt install certbot python3-certbot-nginx# 获取证书sudo certbot --nginx -d example.com -d www.example.com# 自动续期测试sudo certbot renew --dry-run
4.3 安全组策略建议
- 限制SSH访问为特定IP段
- 禁用ROOT用户远程登录
- 定期更新系统补丁(
sudo apt upgrade -y)
五、性能优化方案
5.1 Nginx反向代理配置
server {listen 80;server_name example.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_cache_bypass $http_upgrade;}# 静态资源缓存location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {expires 30d;access_log off;}}
5.2 负载均衡实现
PM2集群模式配置:
pm2 start ecosystem.config.jspm2 scale node-app 4 # 启动4个工作进程
Nginx负载均衡示例:
upstream node_servers {server 127.0.0.1:3000;server 127.0.0.1:3001;server 127.0.0.1:3002;}server {listen 80;location / {proxy_pass http://node_servers;}}
六、监控与维护
6.1 日志管理方案
# 日志轮转配置(/etc/logrotate.d/node-app)/var/log/node-app/*.log {dailymissingokrotate 14compressdelaycompressnotifemptycopytruncate}
6.2 监控工具推荐
- PM2内置监控:
pm2 monit - Prometheus + Grafana:适合中大型系统
- New Relic/Datadog:商业APM解决方案
七、常见问题解决方案
7.1 端口冲突处理
# 查找占用端口的进程sudo lsof -i :3000# 终止进程sudo kill -9 <PID>
7.2 依赖安装失败处理
- 检查Node.js版本兼容性
- 清除npm缓存后重试:
npm cache clean --forcerm -rf node_modules package-lock.jsonnpm install
7.3 内存泄漏排查
- 使用
node --inspect进行调试 - PM2内存监控:
pm2 listpm2 show node-app
八、持续集成建议
推荐部署流程:
- 代码提交触发Webhook
- 服务器自动拉取最新代码
- 执行构建脚本(
npm run build) - 通过PM2重启应用
Git Hook示例(post-receive):
#!/bin/bashTARGET="/var/www/node-app"GIT_DIR="/home/user/repos/node-app.git"BRANCH="master"while read oldrev newrev refdoif [[ $ref = refs/heads/$BRANCH ]];thenecho "Ref $ref received. Deploying ${BRANCH} branch to production..."git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCHcd $TARGETnpm install --productionpm2 reload node-appelseecho "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."fidone
通过以上系统化的部署方案,开发者可以构建出稳定、高效、安全的Node.js云服务架构。实际部署时需根据项目特点调整参数,并建立完善的监控告警机制,确保服务持续可用。