VPS Tutorials
Deploy Node.js on a VPS: systemd, PM2, Nginx and HTTPS
Deploy a supported Node release with private listeners, a non-root account and systemd or PM2. Configure environment files, proxy trust, HTTPS renewal, logs and measured memory limits, then plan reliable releases and rollback.

A project working with npm start locally still needs process supervision, memory limits, HTTPS renewal, useful logs and a recoverable release procedure. This guide uses Ubuntu 24.04 and a Node application listening at 127.0.0.1:3000; the approach also applies to Express, Koa, Nest and Fastify when their startup and shutdown behavior is configured correctly.
An unsupervised node app.js process may terminate when its session ends and does not recreate itself after reboot.
| Requirement | Mechanism |
|---|---|
| Restart after failure and reboot | systemd or PM2 |
| Public hostname and HTTP/HTTPS | Nginx or Caddy |
| Certificate renewal | Certbot schedule or Caddy ACME |
| Diagnosis | Journal, PM2 and proxy logs |
Node's main JavaScript event loop often benefits from strong single-core performance, while workers/native tasks can use additional cores. Daily-user counts do not establish capacity: request cost, SSR, database pools and I/O matter.
| Workload | Starting example | Qualification |
|---|---|---|
| Personal project or small API | 2 vCPU, 2 GB RAM, 40 GB SSD | Optional 2 GB swap may help pressure, not guarantee capacity |
| Production with SSR/builds | 2–4 vCPU, 4 GB RAM, 80 GB SSD | Measure build/runtime memory separately |
| Multiple processes or colocated DB | 4+ vCPU, 8+ GB RAM | Leave capacity for DB and operating system |
next buildandvite buildmay consume more resources than serving requests. Build in CI or a suitable build machine when the VPS is small.- Leave memory headroom and review
--max-old-space-size; heap limits do not include all native buffers or process memory. - Large
node_modulestrees benefit from suitable SSD/NVMe I/O, not just advertised capacity.
RackNerd annual plans and Los Angeles/San Jose locations, Vultr hourly/location choices and Contabo memory/storage offerings are selection examples: verify current price, renewal, availability and actual storage performance. BandwagonHost and DMIT mainland-China-oriented CN2 GIA products address mainland-China connectivity and may cost more; this is not a worldwide latency benefit. Hetzner also requires location/connectivity evaluation, and mainland-China routing concerns do not determine performance for every audience. See VPS sizing.
Prepare the system, reviewing upgrades and reboot requirements:
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl git build-essential ufw
sudo timedatectl set-timezone Asia/Shanghai
The timezone command selects Asia/Shanghai; choose your required IANA zone or UTC instead of applying that regional setting automatically. build-essential supports native builds needed by some versions/platforms of bcrypt, sharp and sqlite3.
One system-wide package option is NodeSource:
curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -
sudo apt install -y nodejs
node -v && npm -v
It installs the 24 series. Review an official installer before running it with privilege and follow its current repository instructions.
The September 2026 advice has changed. As of 16 November 2026, the official schedule lists Node 26 as LTS since 28 October 2026, Node 24 in maintenance since 20 October 2026 through 30 April 2028, and Node 22 in maintenance through 30 April 2027.
- New deployments can evaluate Node 26 LTS after testing dependencies and native modules.
- The Node 24 examples remain suitable for projects tested on supported, patched 24 releases.
- Existing Node 22 projects need an upgrade plan before support ends; do not infer that every maintained release is immediately unusable.
For a version-managed development environment, the original pinned nvm example is:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.7/install.sh | bash
source ~/.bashrc
nvm install 24 && nvm alias default 24
v0.40.7 is a historical example, not the latest release; the official release listing now shows v0.41.0. Verify the installer version you select. systemd does not load interactive nvm initialization. A path such as /home/deploy/.nvm/versions/node/v24.x.x/bin/node must be replaced with the actual installed binary; it may also conflict with ProtectHome. A maintained system-wide Node path can simplify service operation.
Avoid running the application as root:
sudo useradd -r -m -d /srv/app -s /bin/bash appuser
sudo mkdir -p /srv/app/{releases,shared}
sudo chown -R appuser:appuser /srv/app
/srv/app/
├── releases/ # 每次发布的代码,按时间戳分目录
│ ├── 20260920-101500/
│ └── 20260925-090000/
├── current -> releases/20260925-090000
└── shared/
├── .env # 环境变量,不进 git
├── uploads/ # 用户上传文件,软链进 release
└── node_modules/ # 可选,跨 release 复用依赖
Keep versioned code in releases, the active pointer in current and persistent settings/uploads in shared. Reusing node_modules across releases can break dependency isolation; normally install each release from its lockfile or ship an immutable artifact.
For private repository access:
sudo -u appuser ssh-keygen -t ed25519 -C "deploy@vps" -f /srv/app/.ssh/id_ed25519 -N ""
sudo -u appuser cat /srv/app/.ssh/id_ed25519.pub # 贴到仓库的 Deploy Keys
sudo -u appuser git clone [email protected]:your/repo.git /srv/app/releases/20260920-101500
Create /srv/app/.ssh with owner appuser and mode 700 before ssh-keygen; it need not exist after useradd. Use a dedicated read-only repository key, restrict access to it and verify GitHub's host key through a trusted channel. This outbound repository key differs from an inbound CI deployment key. Replace repository and dated release examples; do not overwrite a key already in use.
| Capability | systemd | PM2 |
|---|---|---|
| Dependencies | Operating-system service manager | Maintained npm package |
| Multiple processes | Multiple/template units | Cluster options such as -i max |
| Logs | Journal limits and retention | Files/PM2 logs with rotation |
| Memory handling | MemoryMax enforces a limit; restart policy matters | max_memory_restart periodically triggers restarts, not a hard memory ceiling |
| Reload | systemctl reload requires ExecReload and application support | pm2 reload supports rolling cluster reload with readiness/shutdown handling |
Use one supervisor for the same application. Start with one process and add workers only after checking memory, connection pools and application state.
At /etc/systemd/system/myapp.service:
[Unit]
Description=My Node.js App
After=network.target
[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/srv/app/current
EnvironmentFile=/srv/app/shared/.env
ExecStart=/usr/bin/node --max-old-space-size=768 /srv/app/current/server.js
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
# 资源与安全限制
MemoryMax=1G
LimitNOFILE=65535
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/app/shared
[Install]
WantedBy=multi-user.target
EnvironmentFilepoints toshared/.envso releases do not replace secrets.--max-old-space-size=768must leave headroom underMemoryMax=1Gfor native memory, buffers and the runtime. The 768 MB/1 GB example is not a universal safe margin.ProtectSystem=strictmakes most system paths read-only; declare actual writable locations withReadWritePaths. Keep.envprotected and avoid writing it from the application. A missing writable mount/path can causeEROFS.
The application must actually bind to loopback; PORT alone does not force that. Prepare uploads/log/cache directories with the right ownership.
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
This unit has no ExecReload. systemctl reload will fail; use a tested restart, or design an actual reload/blue-green procedure rather than claiming zero downtime.
sudo npm install -g pm2@7
The 7-series example floats across releases; test and pin the approved version. The package registry currently lists 7.1.2.
The original configuration in current / ecosystem.config.js is:
module.exports = {
apps: [{
name: 'myapp',
script: 'server.js',
instances: 'max',
exec_mode: 'cluster',
max_memory_restart: '700M',
node_args: '--max-old-space-size=640',
env_file: '/srv/app/shared/.env',
error_file: '/srv/app/shared/logs/err.log',
out_file: '/srv/app/shared/logs/out.log',
merge_logs: true,
time: true,
listen_timeout: 10000,
kill_timeout: 5000,
}],
};
PM2's native ecosystem schema does not define env_file. For Node 24/26, use Node's supported --env-file and an explicit cwd instead, for example a reviewed ecosystem.config.cjs:
module.exports = {
apps: [{
name: 'myapp',
cwd: '/srv/app/current',
script: 'server.js',
instances: 1,
exec_mode: 'fork',
node_args: '--env-file=/srv/app/shared/.env --max-old-space-size=640',
max_memory_restart: '700M',
error_file: '/srv/app/shared/logs/err.log',
out_file: '/srv/app/shared/logs/out.log',
time: true,
kill_timeout: 5000
}]
};
Create logs before startup. Use .cjs when a project's package.json selects ESM. Increase instances and choose cluster only after testing readiness, graceful shutdown and total worker memory; PM2 is not a shared session store.
sudo -u appuser pm2 start ecosystem.config.js
sudo -u appuser pm2 save
sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u appuser --hp /srv/app
Run PM2 commands consistently as appuser with its home and explicit configuration path. pm2 startup must generate the intended user's startup service, including -u appuser; inspect the generated unit and save the tested process list. Verify reboot behavior.
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 20M
pm2 set pm2-logrotate:retain 7
Install/configure log rotation in the same user's PM2 instance. Both custom log paths and ~/.pm2/logs need retention. Cluster workers have independent in-memory sessions, caches and timers; setInterval can run once per worker. Move scheduled work to a deliberate single scheduler or distributed lock design.
Keep the app at 127.0.0.1:3000; publish 80/443 through the proxy:
sudo apt install -y nginx
Save the reviewed virtual host at /etc/nginx/sites-available/api.example.com:
upstream myapp_backend {
server 127.0.0.1:3000;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name api.example.com;
client_max_body_size 20m;
access_log /var/log/nginx/api.access.log;
error_log /var/log/nginx/api.error.log warn;
location / {
proxy_pass http://myapp_backend;
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_set_header Connection "";
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_buffering on;
}
# WebSocket / SSE
location /socket.io/ {
proxy_pass http://myapp_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s;
proxy_buffering off;
}
}
sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
X-Forwarded-Forpreserves forwarded client information, but trust only the actual proxy chain. A backend may otherwise see127.0.0.1.app.set('trust proxy', 1)assumes exactly one trusted hop; do not apply it when clients can bypass the proxy or inject trusted headers.client_max_body_sizedefaults to 1 MB in ordinary Nginx; the example changes it to 20m. Align application/CDN limits and proxy security controls.- Use
proxy_buffering offin the actual SSE location where buffering causes delay. WebSockets need upgrade handling; the /socket.io/ location does not automatically cover all stream routes. Add forwarded protocol/client headers there too when the application relies on them. proxy_read_timeoutis normally 60s between upstream reads, not a universal total-request timeout. Long jobs often belong in a queue rather than an indefinitely open request.
Caddy can replace the Nginx frontend:
api.example.com {
reverse_proxy 127.0.0.1:3000
}
Its automatic HTTPS still requires suitable DNS, reachability and persistent certificate storage. See Caddy reverse proxy.
With Nginx, use the installed Certbot integration:
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d api.example.com --redirect --agree-tos -m [email protected]
Replace domain/email and verify A/AAAA records and ports first. Check the scheduler for the actual package/snap:
systemctl list-timers | grep certbot
sudo certbot renew --dry-run
Monitor certificate expiry and application availability. See renewal diagnosis.
Keep .env under shared/:
sudo -u appuser touch /srv/app/shared/.env
sudo chmod 600 /srv/app/shared/.env
sudo chown appuser:appuser /srv/app/shared/.env
NODE_ENV=production
PORT=3000
DATABASE_URL=postgres://app:[email protected]:5432/appdb
SESSION_SECRET=换成 openssl rand -hex 32 生成的值
Replace every illustrative password and secret. systemd EnvironmentFile parses assignments but does not run shell commands or perform arbitrary shell interpolation; PM2 here uses Node's env-file parser. Verify the intended values without printing credentials.
- Do not commit
.env. A.env.examplecan document keys with safe placeholders. - Keep the database on loopback/private networking; see public database risks.
- Plan
SESSION_SECRETrotation: sessions signed with an old key may become invalid unless the application supports a transition.
The source's release-directory illustration is:
#!/usr/bin/env bash
set -euo pipefail
APP=/srv/app
RELEASE=$APP/releases/$(date +%Y%m%d-%H%M%S)
sudo -u appuser git clone --depth 1 [email protected]:your/repo.git "$RELEASE"
ln -sfn "$APP/shared/.env" "$RELEASE/.env"
ln -sfn "$APP/shared/uploads" "$RELEASE/uploads"
cd "$RELEASE"
sudo -u appuser npm ci --omit=dev
ln -sfn "$RELEASE" "$APP/current"
sudo systemctl reload myapp # 或 pm2 reload myapp
# 只保留最近 5 个版本
ls -1dt $APP/releases/* | tail -n +6 | xargs -r rm -rf
Before production use, fix the missing build/readiness steps, ownership and reload behavior. Install build dependencies when building TypeScript/SSR, or deploy a CI-built locked artifact. Avoid sharing a mutable dependency tree across releases. Stage an atomic same-filesystem symlink replacement, and retain both the active and previous validated release. The ls/xargs cleanup is unsafe with unusual names and can remove a still-needed rollback; explicitly select reviewed inactive release directories instead.
systemctl reload requires a configured ExecReload and application behavior; listening for SIGUSR2 alone does not teach systemd how to reload. A basic restart can interrupt requests. For continuity, start a separate new instance, test readiness, switch proxy traffic and drain the old instance. Rollback must account for database migrations, not just a symlink.
Use set -euo pipefail with explicit checks. A failed npm ci must stop before changing current. Validate the exact release commit and health endpoint, then keep a tested recovery path.
# systemd 方式
sudo journalctl -u myapp -n 100 --no-pager
sudo journalctl -u myapp -f
# PM2 方式
pm2 logs myapp --lines 100
pm2 describe myapp
# Nginx
sudo tail -f /var/log/nginx/api.error.log
Run PM2 diagnosis under the application account. Retain useful journal data while controlling space:
sudo journalctl --vacuum-size=500M
sudo sed -i 's/^#\?SystemMaxUse=.*/SystemMaxUse=500M/' /etc/systemd/journald.conf
sudo systemctl restart systemd-journald
This affects system-wide journal retention; review other services' needs. A sed only changes an existing matching line, so verify the resulting effective setting or use a deliberate journald drop-in.
502: inspect systemctl status myapp and actual listeners. localhost may resolve differently from 127.0.0.1; use the deliberate address family and check proxy logs.
EADDRINUSE: identify the listener with sudo ss -lntp 'sport = :3000'; see port conflicts.
EACCES on port 80: prefer a reverse proxy. sudo setcap 'cap_net_bind_service=+ep' $(which node) illustrates granting a capability to Node but broadens that binary's privileges, may fail for a symlink and can disappear on upgrade. A narrowly scoped systemd capability policy is another reviewed design; do not run the whole app as root.
Growing memory/OOM: --max-old-space-size limits heap, not all RSS. Inspect cgroup/kernel events and use protected heap diagnostics, leaving room for snapshot overhead. Swap does not repair a leak; see zram and swap.
EMFILE: inspect the process's LimitNOFILE and system-wide fs.file-max, and fix leaked descriptors before blindly raising limits. See service log diagnosis.
name: deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy over SSH
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.VPS_HOST }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
script: /srv/app/deploy.sh
The example uses host, user and deployment-key secrets. Use a dedicated revocable inbound key, a restricted remote script and verified host fingerprint. Pin third-party Actions to an approved immutable commit rather than relying indefinitely on a moving major tag. Serialize deployments, deploy the expected commit/artifact and ensure the remote script exits on failure. Keep any required service-control privilege narrowly scoped. See self-hosted runners.
Dokploy or Coolify can manage build/deployment workflows, but add a platform whose data, permissions and upgrades also need maintenance.
- Back up databases and uploads and test recovery; a Git repository does not contain all runtime data.
- Configure traffic and quota alerts for the actual plan's limits.
- Use external availability checks and certificate-expiry monitoring; setup time depends on your environment.
- Verify
unattended-upgradessources/policy and reboot requirements instead of assuming every update is automatically covered. - Record normal TTFB, worker RSS, error rate and database usage for comparison.