在 Ubuntu 上部署 Node.js 应用的实用步骤
一 准备与安装
- 更新系统并安装基础工具:
- sudo apt update && sudo apt upgrade -y
- sudo apt install -y curl git build-essential
- 安装 Node.js(推荐 LTS,使用 NodeSource 仓库):
- 选择版本(示例为 18.x,可按需替换为 20.x):
- curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
- 安装:
- sudo apt-get install -y nodejs
- 验证:
- 说明:NodeSource 安装后二进制名为 nodejs(部分系统可能同时提供 node 软链);build-essential 用于编译原生依赖。
二 部署应用代码
- 方式 A(Git 拉取):
- git clone https://github.com/your-username/your-project.git
- cd your-project
- 方式 B(本地上传):
- 安装依赖与构建:
- npm ci --only=production(或 npm install --production)
- 如有构建步骤(TypeScript、前端静态资源等)执行:npm run build
- 环境变量(示例):
- 在 ~/.bashrc、~/.profile 或 /etc/environment 中设置,例如:
- echo ‘export NODE_ENV=production’ >> ~/.bashrc
- echo ‘export PORT=3000’ >> ~/.bashrc
- source ~/.bashrc
- 注意:确保应用监听 0.0.0.0(或 127.0.0.1 且仅配合反向代理),端口与后续 Nginx 配置一致。
三 进程管理与自启动
- 使用 PM2 守护进程:
- 全局安装:sudo npm install -g pm2
- 启动(按项目脚本):
- pm2 start npm --name “my-app” – run start
- 或:pm2 start app.js --name “my-app”
- 常用命令:
- pm2 status
- pm2 logs my-app
- pm2 restart my-app
- pm2 stop my-app
- 设置开机自启动:
- pm2 startup
- 按提示执行生成的命令,然后:pm2 save
- 说明:PM2 会在崩溃或重启后自动拉起应用,适合生产环境长期运行。
四 配置 Nginx 反向代理与 HTTPS
- 安装 Nginx:
- sudo apt install -y nginx
- 配置站点(示例:/etc/nginx/sites-available/your-domain):
- 建议为站点单独创建配置文件并软链到 sites-enabled
- 示例配置:
- server {
listen 80;
server_name your-domain.com www.your-domain.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
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;
}
}
- 启用站点与生效:
- sudo ln -s /etc/nginx/sites-available/your-domain /etc/nginx/sites-enabled/
- sudo nginx -t && sudo systemctl reload nginx
- 防火墙放行:
- sudo ufw allow ‘Nginx Full’
- HTTPS(推荐):
- 使用 Certbot 获取 Let’s Encrypt 证书并自动配置 Nginx:
- sudo apt install -y certbot python3-certbot-nginx
- sudo certbot --nginx -d your-domain.com -d www.your-domain.com
- 说明:Nginx 负责静态资源、压缩、缓存与 TLS,Node.js 专注业务。
五 常见问题与优化
- 端口与监听地址:应用应监听 3000(或自定义端口),并确保与 Nginx 的 proxy_pass 一致;如需外部直连,监听 0.0.0.0 并配合防火墙。
- 权限与安全:
- 避免使用 root 运行应用;最小权限原则
- 将 .env 等敏感文件加入 .gitignore,服务器上单独管理
- 日志与监控:
- PM2 日志:pm2 logs;监控:pm2 monit
- Nginx 日志:/var/log/nginx/access.log 与 error.log
- 构建与依赖:
- 生产环境使用 npm ci;如有原生模块,提前安装 build-essential
- 优雅重启与零停机:
- pm2 reload my-app(配合集群模式可零停机)
- 静态资源:由 Nginx 直接服务,减轻 Node.js 负载
- 版本管理(可选):如需多版本并存,使用 NVM 切换 Node.js 版本。