一、部署前的基础准备
1.1 云服务器选型与配置
选择云服务器时需综合考虑项目规模、并发量和预算。对于中小型Node.js应用,推荐配置为:2核CPU、4GB内存、50GB SSD存储,带宽根据预期流量选择(建议初期3-5Mbps)。操作系统建议选择Ubuntu 22.04 LTS或CentOS 8,这两个系统对Node.js有完善的社区支持。
1.2 服务器安全加固
部署前必须完成基础安全配置:
- 修改默认SSH端口(如从22改为2222)
- 禁用root用户远程登录
- 配置SSH密钥认证
- 安装fail2ban防止暴力破解
- 配置防火墙规则(仅开放80/443/2222等必要端口)
示例防火墙配置(Ubuntu):
sudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw allow 2222/tcpsudo ufw allow 80/tcpsudo ufw allow 443/tcpsudo ufw enable
1.3 开发环境同步
确保本地开发环境与生产环境一致:
- Node.js版本(建议使用nvm管理多版本)
- npm/yarn版本
- 项目依赖版本(通过package-lock.json锁定)
二、Node.js环境部署
2.1 Node.js安装
推荐使用nvm安装Node.js,便于版本切换:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bashsource ~/.bashrcnvm install --ltsnvm use --lts
2.2 项目文件传输
推荐使用rsync进行文件同步,比scp更高效:
rsync -avz --exclude='node_modules/' --exclude='.env' \/local/project/path/ \username@server_ip:/remote/project/path/
2.3 环境变量配置
使用.env文件管理环境变量(需添加到.gitignore):
DB_HOST=localhostDB_PORT=5432JWT_SECRET=your_secret_key
在项目中通过dotenv加载:
require('dotenv').config();console.log(process.env.DB_HOST);
三、进程管理与持久化
3.1 PM2进程管理
PM2是Node.js最流行的进程管理器,提供:
- 进程守护
- 自动重启
- 负载均衡
- 日志管理
安装与基本使用:
npm install pm2 -gpm2 start app.js --name "my-app"pm2 save # 保存进程列表pm2 startup # 生成开机启动脚本
生产环境推荐配置:
// ecosystem.config.jsmodule.exports = {apps: [{name: "my-app",script: "app.js",instances: "max", // 或指定具体数量exec_mode: "cluster",env: {NODE_ENV: "production"},error_file: "/var/log/my-app-err.log",out_file: "/var/log/my-app-out.log"}]};
3.2 日志管理方案
推荐使用winston+PM2日志系统组合:
const winston = require('winston');const { combine, timestamp, printf } = winston.format;const logFormat = printf(({ level, message, timestamp }) => {return `${timestamp} ${level}: ${message}`;});const logger = winston.createLogger({level: 'info',format: combine(timestamp(),logFormat),transports: [new winston.transports.File({ filename: 'combined.log' }),new winston.transports.Console()]});module.exports = logger;
四、Nginx反向代理配置
4.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 /static/ {alias /var/www/my-app/static/;expires 30d;}}
4.2 HTTPS配置
使用Let’s Encrypt免费证书:
sudo apt install certbot python3-certbot-nginxsudo certbot --nginx -d example.com -d www.example.com
自动续期配置:
sudo certbot renew --dry-run# 添加到crontab每月检查0 3 * * * /usr/bin/certbot renew --quiet
五、自动化部署方案
5.1 Git Hook自动部署
创建服务器端裸仓库:
mkdir -p /var/repo/my-app.gitcd /var/repo/my-app.gitgit init --bare
配置post-receive钩子:
cat > hooks/post-receive <<EOF#!/bin/bashTARGET="/var/www/my-app"GIT_DIR="/var/repo/my-app.git"BRANCH="master"while read oldrev newrev refdobranch=`echo $ref | cut -d'/' -f3`if [ "$branch" = "$BRANCH" ]; thenecho "Ref $ref received. Deploying ${branch} to production..."git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $branchcd $TARGETnpm install --productionpm2 reload my-appelseecho "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."fidoneEOFchmod +x hooks/post-receive
5.2 CI/CD集成方案
推荐使用GitHub Actions示例配置:
name: Deploy Node.js Appon:push:branches: [ main ]jobs:deploy:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v2- name: Install Node.jsuses: actions/setup-node@v2with:node-version: '16'- name: Install dependenciesrun: npm ci- name: Deploy to Serveruses: appleboy/ssh-action@masterwith:host: ${{ secrets.SERVER_IP }}username: ${{ secrets.SERVER_USER }}key: ${{ secrets.SSH_PRIVATE_KEY }}script: |cd /var/www/my-appgit pull origin mainnpm ci --productionpm2 reload my-app
六、常见问题解决方案
6.1 端口占用问题
查找并终止占用端口的进程:
sudo lsof -i :3000sudo kill -9 <PID>
6.2 内存泄漏排查
使用PM2内存监控:
pm2 monit
或生成堆快照分析:
# 安装诊断工具npm install -g node-heapdump# 在代码中添加const heapdump = require('heapdump');app.get('/dump', (req, res) => {const filename = `/tmp/heapdump-${Date.now()}.heapsnapshot`;heapdump.writeSnapshot(filename, (err) => {if (err) return res.status(500).send('Error creating dump');res.download(filename);});});
6.3 性能优化建议
-
启用Gzip压缩(Nginx配置):
gzip on;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
-
启用HTTP/2(需HTTPS):
listen 443 ssl http2;
-
使用CDN加速静态资源
七、监控与维护
7.1 基础监控指标
推荐监控项:
- CPU使用率
- 内存使用量
- 响应时间(P90/P99)
- 错误率
- 请求量
7.2 告警配置示例
使用PM2的邮件告警:
pm2 set pm2:email your@email.compm2 set pm2:smtp_host smtp.example.compm2 set pm2:smtp_port 587pm2 set pm2:smtp_user userpm2 set pm2:smtp_password pass
或在ecosystem.config.js中配置:
module.exports = {apps: [{// ...其他配置pm2_env: {EMAIL: "your@email.com",SMTP_HOST: "smtp.example.com"}}]};
通过以上系统化的部署方案,开发者可以构建出稳定、高效、安全的Node.js生产环境。实际部署时建议先在测试环境验证所有流程,再逐步迁移到生产环境。定期回顾和优化部署流程,能够持续提升应用的可靠性和运维效率。