Debian云服务器上部署Node.js项目的实操指南
一 准备与基础环境
sudo apt update && sudo apt upgrade -y && sudo apt install -y curl wget git build-essentialcurl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - && sudo apt-get install -y nodejscurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bashsource ~/.bashrcnvm install --lts && nvm use --lts && nvm alias default nodenode -v、npm -vmkdir ~/.npm-global && npm config set prefix '~/.npm-global'echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc && source ~/.bashrcnpm install -g npm@latest pm2二 部署与进程管理
git clone <repo> /opt/myapp && cd /opt/myapptar -xvf project.tar.gz -C /opt && cd /opt/projectnpm ci --only=production(或 npm install 含 devDependencies)npm run buildpm2 start app.js --name "myapp" 或 pm2 start npm --name "myapp" -- run startecosystem.config.js(推荐)
module.exports = {
apps: [{
name: 'myapp',
script: 'app.js',
instances: 'max',
exec_mode: 'cluster',
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: { NODE_ENV: 'development' },
env_production: { NODE_ENV: 'production', PORT: 3000 }
}]
};
pm2 start ecosystem.config.js --env productionpm2 list、pm2 logs myapp、pm2 restart/reload myapp、pm2 monitpm2 startup 并按提示执行生成的命令三 反向代理与域名 HTTPS
sudo apt install -y nginx/etc/nginx/sites-available/defaultserver {
listen 80;
server_name your_domain_or_ip;
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;
}
}
sudo nginx -t && sudo systemctl reload nginxsudo ufw allow 'Nginx Full'sudo apt install -y certbot python3-certbot-nginxsudo certbot --nginx -d your_domain_or_ipsudo crontab -e 加入 0 12 * * * /usr/bin/certbot renew --quiet四 自动化部署与多实例扩展
ecosystem.config.js 增加:deploy: {
production: {
user: 'deploy',
host: 'YOUR_SERVER_IP',
ref: 'origin/main',
repo: 'git@github.com:org/repo.git',
path: '/opt/myapp',
'post-deploy': 'npm ci --only=production && pm2 reload ecosystem.config.js --env production'
}
}
pm2 deploy production setuppm2 deploy production updatepm2 start app.js -i max 或在配置中 instances: 'max', exec_mode: 'cluster'upstream node_app {
server 10.0.0.11:3000;
server 10.0.0.12:3000;
}
server {
listen 80;
location / { proxy_pass http://node_app; }
}
sudo systemctl reload nginxprom-client 暴露指标,Prometheus 抓取 :3000/metrics,Grafana 可视化五 常见问题与排查清单
sudo npm -g;使用 NVM 或配置 ~/.npm-global 的 PATHenv 与 env_production;前端静态资源构建产物路径与 public 或 dist 保持一致pm2 logs myapp -f、pm2 monit;Nginx 错误日志:/var/log/nginx/error.logpm2 reload(零停机);回滚执行 pm2 deploy production revertmax_memory_restart;必要时增加实例数或垂直扩容