在 VPS 上部署 Node.js 应用 - systemd + Nginx,无需 Docker

分步教程:通过 NodeSource 安装 Node.js 22、独立应用用户、systemd 自动重启、Nginx 反向代理与 HTTPS。真实命令,15 分钟完成部署。

没有 Docker,没有 PaaS,没有魔法。Node.js 加 systemd 和 Nginx,是一套扛得住重启、崩溃和流量的组合:而且每一部分都看得懂。

1. 安装 Node.js

apt update && apt install -y curl
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt install -y nodejs
node --version

2. 创建应用专用用户

切勿以 root 身份运行 Web 应用。使用独立用户,万一应用被攻破也能限制损失。

adduser --system --group --home /opt/myapp app
mkdir -p /opt/myapp
chown app:app /opt/myapp

3. 上传应用

在您的电脑上通过 SSH 使用 rsync:无需 Git 服务器:

rsync -avz --exclude node_modules ./app/ root@YOUR_SERVER_IP:/opt/myapp/

在服务器上安装依赖,并先在前台测试一次:

cd /opt/myapp
sudo -u app npm ci --omit=dev
sudo -u app PORT=3000 node server.js

应用必须监听 `127.0.0.1:3000`,而不是公网接口。面向互联网的是 Nginx。

4. 用 systemd 保持运行

cat > /etc/systemd/system/myapp.service <<'EOF'
[Unit]
Description=My Node.js app
After=network-online.target
[Service]
User=app
WorkingDirectory=/opt/myapp
Environment=NODE_ENV=production
Environment=PORT=3000
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now myapp
systemctl status myapp

崩溃了?三秒后自动重启。服务器重启?自动启动。部署新版本?`rsync`,然后 `systemctl restart myapp`。

5. 前置 Nginx

apt install -y nginx
cat > /etc/nginx/sites-available/myapp <<'EOF'
server {
    listen 80;
    server_name example.com;
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF
ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
nginx -t && systemctl reload nginx

然后把域名的 A 记录指向服务器并添加 HTTPS:完整教程见 Nginx 与 HTTPS 指南。

6. 查看日志

journalctl -u myapp -f --no-pager
tail -f /var/log/nginx/error.log

应用的控制台输出会自动进入 journald:无需配置任何日志文件。

常见问题

需要 PM2 吗?

其实不需要。对于单台服务器,PM2 能做的 systemd 都能做:自动重启、开机启动、日志:还不用额外依赖。只有需要以集群模式运行多个 Node 进程时,PM2 才有意义。

Node 应用需要多少内存?

典型的 Express 应用空闲时约占 80–150 MB。2 GB 服务器可以让它与 Nginx、PostgreSQL 一起轻松运行;webpack 等构建步骤最耗内存,建议在 CI 或本机完成构建。

如何零停机部署新版本?

用 rsync 同步新代码,然后重启:中断不到一秒,因为 systemd 会立即重新拉起进程。要做到零停机,可以运行两个端口并切换 Nginx 上游,但大多数项目用不到。

这套组合在 €12/月的 Core VPS 4 上绰绰有余。

相关内容

查看套餐指南常见问题