Node.js项目云服务器部署全指南:从零到生产环境实践

作者:狼烟四起2025.10.29 16:11浏览量:0

简介:本文详细介绍如何将Node.js项目部署到云服务器,涵盖环境准备、安全配置、自动化部署等关键环节,帮助开发者快速构建稳定的生产环境。

一、云服务器选择与前期准备

1.1 云服务器类型对比

主流云服务商(如阿里云、腾讯云、AWS等)均提供多种实例类型:

  • 计算优化型:适合高并发API服务(如c6.large,2vCPU+4GB内存)
  • 内存优化型:适合缓存密集型应用(如r6i.xlarge,4vCPU+32GB内存)
  • 突发性能型:适合开发测试环境(如t6.small,1vCPU+1GB内存)

建议根据项目QPS和内存占用选择实例,初期可选择2核4G配置,后续通过弹性伸缩横向扩展。

1.2 操作系统选择

推荐使用Ubuntu 22.04 LTSCentOS 8

  • Ubuntu优势:最新软件包支持,完善的snap包管理
  • CentOS优势:企业级稳定性,兼容RHEL生态

通过SSH连接服务器后,首先执行系统更新:

  1. # Ubuntu系统
  2. sudo apt update && sudo apt upgrade -y
  3. # CentOS系统
  4. sudo yum update -y

二、Node.js环境部署

2.1 版本管理工具安装

推荐使用nvm进行多版本管理:

  1. curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash
  2. source ~/.bashrc
  3. nvm install --lts
  4. nvm use --lts

验证安装:

  1. node -v # 应输出类似v18.16.0
  2. npm -v # 应输出类似9.5.1

2.2 项目依赖安装

将项目代码克隆至服务器后,需注意:

  1. 使用--production参数跳过devDependencies
  2. 配置npm镜像加速(如使用淘宝源)
  1. # 配置淘宝镜像
  2. npm config set registry https://registry.npmmirror.com
  3. # 安装生产依赖
  4. npm install --production

三、生产环境配置

3.1 进程管理工具选择

推荐使用PM2进行进程管理:

  1. npm install pm2 -g
  2. pm2 startup # 生成开机自启脚本
  3. pm2 save # 保存当前进程列表

启动配置示例(ecosystem.config.js):

  1. module.exports = {
  2. apps: [{
  3. name: 'api-service',
  4. script: './dist/main.js',
  5. instances: 'max', // 自动根据CPU核心数启动
  6. exec_mode: 'cluster',
  7. env: {
  8. NODE_ENV: 'production',
  9. PORT: 3000
  10. },
  11. error_file: '/var/log/pm2/api-error.log',
  12. out_file: '/var/log/pm2/api-out.log'
  13. }]
  14. };

3.2 反向代理配置

使用Nginx作为反向代理:

  1. server {
  2. listen 80;
  3. server_name api.example.com;
  4. location / {
  5. proxy_pass http://127.0.0.1:3000;
  6. proxy_set_header Host $host;
  7. proxy_set_header X-Real-IP $remote_addr;
  8. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  9. }
  10. # 静态资源缓存
  11. location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  12. expires 30d;
  13. access_log off;
  14. }
  15. }

四、安全加固方案

4.1 防火墙配置

使用ufw(Ubuntu)或firewalld(CentOS)限制访问:

  1. # Ubuntu系统
  2. sudo ufw allow 22/tcp # SSH端口
  3. sudo ufw allow 80/tcp # HTTP端口
  4. sudo ufw allow 443/tcp # HTTPS端口
  5. sudo ufw enable
  6. # CentOS系统
  7. sudo firewall-cmd --permanent --add-port=22/tcp
  8. sudo firewall-cmd --permanent --add-port=80/tcp
  9. sudo firewall-cmd --reload

4.2 SSH安全优化

  1. 修改默认SSH端口(编辑/etc/ssh/sshd_config
  2. 禁用root登录:
    1. PermitRootLogin no
  3. 使用SSH密钥认证:
    1. # 客户端生成密钥对
    2. ssh-keygen -t rsa -b 4096
    3. # 上传公钥到服务器
    4. ssh-copy-id -i ~/.ssh/id_rsa.pub user@server_ip

五、自动化部署方案

5.1 Git Hook自动部署

在项目根目录创建.git/hooks/post-receive

  1. #!/bin/bash
  2. TARGET="/var/www/api"
  3. GIT_DIR="/var/repo/api.git"
  4. BRANCH="main"
  5. while read oldrev newrev ref
  6. do
  7. if [[ $ref = refs/heads/$BRANCH ]];
  8. then
  9. echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
  10. git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
  11. cd $TARGET
  12. npm install --production
  13. pm2 reload ecosystem.config.js
  14. else
  15. echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
  16. fi
  17. done

5.2 CI/CD集成方案

以GitHub Actions为例:

  1. name: Deploy to Production
  2. on:
  3. push:
  4. branches: [ main ]
  5. jobs:
  6. deploy:
  7. runs-on: ubuntu-latest
  8. steps:
  9. - uses: actions/checkout@v3
  10. - name: Install Node.js
  11. uses: actions/setup-node@v3
  12. with:
  13. node-version: '18'
  14. - name: Install dependencies
  15. run: npm ci --production
  16. - name: Deploy to server
  17. uses: appleboy/ssh-action@master
  18. with:
  19. host: ${{ secrets.SERVER_IP }}
  20. username: ${{ secrets.SERVER_USER }}
  21. key: ${{ secrets.SSH_PRIVATE_KEY }}
  22. script: |
  23. cd /var/www/api
  24. git pull origin main
  25. npm ci --production
  26. pm2 reload ecosystem.config.js

六、监控与维护

6.1 日志管理方案

推荐使用winston+logstash组合:

  1. const winston = require('winston');
  2. const { combine, timestamp, json } = winston.format;
  3. const logger = winston.createLogger({
  4. level: 'info',
  5. format: combine(
  6. timestamp(),
  7. json()
  8. ),
  9. transports: [
  10. new winston.transports.File({
  11. filename: '/var/log/api/error.log',
  12. level: 'error'
  13. }),
  14. new winston.transports.File({
  15. filename: '/var/log/api/combined.log'
  16. })
  17. ]
  18. });

6.2 性能监控工具

  • PM2监控pm2 monit
  • New Relic:APM解决方案
  • Prometheus+Grafana:自定义监控面板

七、常见问题处理

7.1 端口冲突解决方案

  1. # 查找占用端口的进程
  2. sudo lsof -i :3000
  3. # 终止指定进程
  4. sudo kill -9 <PID>

7.2 内存泄漏排查

  1. 使用pm2 list查看内存占用
  2. 通过pm2 logs检查错误日志
  3. 使用Chrome DevTools的Node.js调试功能

7.3 依赖安装失败处理

  1. 清除npm缓存:
    1. npm cache clean --force
  2. 检查node版本与依赖兼容性
  3. 尝试使用yarn替代npm

八、最佳实践总结

  1. 环境隔离:开发/测试/生产环境严格分离
  2. 配置管理:使用dotenv或config模块管理环境变量
  3. 回滚机制:保留最近3个成功部署版本
  4. 灾备方案:重要数据定时备份至对象存储
  5. 性能基线:建立QPS、响应时间等关键指标

通过以上系统化的部署方案,开发者可以构建出高可用、易维护的Node.js生产环境。实际部署时建议先在测试环境验证所有流程,再逐步推广到生产环境。