Running Node.js on your own server, from first deploy to safe restarts

Node.js on a VPS needs three things: a current LTS release, systemd to keep the process alive, and nginx in front of two copies of the app so a restart drops nobody. This page builds that on Ubuntu 24.04 and explains why memory, not traffic, is what usually kills a Node server.

Updated: · Prices in the text are with the public IP (₼10 a month) unless stated otherwise.

Install an LTS release, not the distribution package

The Ubuntu 24.04 archive carries Node 18, which stopped receiving fixes in April 2025. Take an even-numbered LTS from NodeSource; Node 24 is maintained until April 2028. Download the setup script and read it before running it as root:

curl -fsSL https://deb.nodesource.com/setup_24.x -o /tmp/nodesource.sh
less /tmp/nodesource.sh
sudo bash /tmp/nodesource.sh
sudo apt install -y nodejs nginx git
sudo adduser --system --group --home /srv/nodeapp --shell /usr/sbin/nologin nodeapp
sudo -u nodeapp mkdir -p /srv/nodeapp/releases /srv/nodeapp/shared

Each deploy gets its own folder in releases; the symlink current points to the live one. Uploaded files belong in shared, because everything else is replaceable.

A template unit: one file, many instances

The @ in the file name lets systemd start several copies. %i becomes the port.

# /etc/systemd/system/nodeapp@.service
[Unit]
Description=Node app on port %i
Wants=network-online.target
After=network-online.target

[Service]
User=nodeapp
Group=nodeapp
WorkingDirectory=/srv/nodeapp/current
EnvironmentFile=/etc/nodeapp.env
Environment=NODE_ENV=production PORT=%i
ExecStart=/usr/bin/node --max-old-space-size=768 server.js
Restart=always
RestartSec=2
TimeoutStopSec=20
MemoryMax=1100M
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/srv/nodeapp/shared

[Install]
WantedBy=multi-user.target

Keep secrets in /etc/nodeapp.env as KEY=value lines, owner root, mode 600: systemd reads it before dropping privileges. Do not add MemoryDenyWriteExecute; the V8 JIT compiler cannot work with it.

The memory limits above suit a 4 GB server; the table further down gives others. PM2 is fine on a laptop. On a server it adds a second process manager beside the one Linux already has, with its own logs and start-up hook.

Teach the app to stop politely

systemctl restart sends SIGTERM. Without a handler Node dies at once and open requests fail.

const server = app.listen(process.env.PORT, '127.0.0.1')
server.keepAliveTimeout = 65_000

process.on('SIGTERM', () => {
  server.close(() => process.exit(0))
  setTimeout(() => process.exit(1), 15_000).unref()
})

The keep-alive value is longer than the 60 seconds nginx keeps idle upstream connections, so Node never closes one that nginx is about to reuse. That mismatch is a common source of rare, unexplained 502 errors. Close database pools in the same handler, and provide a /health route that answers 200 only when the database responds.

nginx in front of two ports

# /etc/nginx/sites-available/nodeapp
upstream nodeapp {
    server 127.0.0.1:3001 max_fails=1 fail_timeout=5s;
    server 127.0.0.1:3002 max_fails=1 fail_timeout=5s;
    keepalive 16;
}
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      '';
}
server {
    listen 80;
    server_name api.example.az;

    location / {
        proxy_pass http://nodeapp;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        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_connect_timeout 2s;
        proxy_next_upstream error timeout;
    }
}

Link it into sites-enabled, run sudo nginx -t, then add HTTPS with the certificate guide. If you use Socket.IO with long polling, add ip_hash; to the upstream and a Redis adapter, because two processes do not share rooms. Leave ports 3001 and 3002 closed in the firewall; the hardening guide has the rules.

A rolling deploy script

#!/usr/bin/env bash
# /usr/local/bin/deploy-nodeapp REPO TAG   (run with sudo)
set -euo pipefail
repo=$1; tag=$2
rel=/srv/nodeapp/releases/$(date +%Y%m%d-%H%M%S)

sudo -H -u nodeapp git clone --depth 1 --branch "$tag" "$repo" "$rel"
cd "$rel"
sudo -H -u nodeapp npm ci
sudo -H -u nodeapp npm run build --if-present
sudo -H -u nodeapp npm prune --omit=dev
ln -sfn "$rel" /srv/nodeapp/current

for port in 3001 3002; do
  systemctl restart "nodeapp@$port"
  ok=0
  for _ in {1..20}; do
    if curl -fs "http://127.0.0.1:$port/health" >/dev/null; then ok=1; break; fi
    sleep 1
  done
  [ "$ok" = 1 ] || { echo "port $port is not healthy, stopping"; exit 1; }
done
ls -1dt /srv/nodeapp/releases/* | tail -n +6 | xargs -r rm -rf

While 3001 restarts, 3002 serves everyone, and the script stops if the new version never becomes healthy, leaving the old code running on the second port. To roll back, point current at the previous folder and restart both. Enable the copies once: sudo systemctl enable nodeapp@3001 nodeapp@3002. For a private repository give the nodeapp user a read-only deploy key.

Database migrations must work with both versions at the same time: add a column in one release, stop using the old one in the next, drop it in a third.

How Node uses memory

The figure you see in ps is not just the JavaScript heap. Buffers, native modules and code live outside it, so a process limited to 768 MB of heap can occupy 1000 MB. Set both limits: --max-old-space-size makes the garbage collector work harder before failing, and MemoryMax stops a leak from taking the database down with it.

Server RAMAlso on the serverInstances × heap (starting point)
1 GBnothing heavy1 × 400 MB
2 GBsmall PostgreSQL2 × 384 MB
4 GBPostgreSQL, Redis2 × 768 MB
8 GB, 4 vCPUdatabase elsewhere4 × 1,200 MB

Read the failure before adding RAM. JavaScript heap out of memory in journalctl -u 'nodeapp@*' means your own limit was reached: look for growing arrays, maps and listeners. An oom-kill line in journalctl -k means the machine or the unit limit was exceeded. If RSS climbs steadily under constant traffic for a day, it is a leak, and a larger plan only postpones the restart.

Processor use is simpler: JavaScript runs on one thread per process, so one instance cannot use a second vCPU. Start one instance per vCPU, and move image resizing or PDF generation into a worker or a queue.

Choosing a plan

  • Basic₼27.90/mo

    2 vCPU · 2 GB RAM · 40 GB NVMe

    Public IP +₼10/mo, With public IP: ₼37.90/mo

  • Standard₼39.90/mo

    2 vCPU · 4 GB RAM · 60 GB NVMe

    Public IP +₼10/mo, With public IP: ₼49.90/mo

  • Professional₼73.90/mo

    4 vCPU · 8 GB RAM · 100 GB NVMe

    Public IP +₼10/mo, With public IP: ₼83.90/mo

Prices in manat (AZN), billed monthly. The public IP is +₼10 a month and is assigned automatically.

Basic (2 vCPU, 2 GB RAM, 40 GB NVMe) runs a small API in two light instances. Standard is the practical minimum for the two-instance layout with a full local database; it is ₼49.90 a month with public IP, which is ₼10 of that. Professional gives four instances a vCPU each. Building Next.js or another large frontend can need more memory than serving it: build in CI and copy the result, or add swap for the build. If you already ship images, compare this layout with Docker on a VPS or managed containers.

Node.js server questions

Do I need PM2 if I use systemd?

No. systemd restarts the process, starts it at boot, limits memory and collects logs. PM2 cluster mode overlaps with running two units behind nginx.

How many Node.js apps fit on one VPS?

Add up measured RSS, not guesses. A small Express API often sits around 80–150 MB, so several fit into 2 GB beside nginx. A server-rendered frontend may take 300 MB or more on its own.

Can I run Node directly on ports 80 and 443?

You can, but then a restart closes the port, and TLS, compression and static files become your code's work. Binding to localhost behind nginx is easier to operate.

Why does my Node process restart at night?

Look in the journal for status=6/ABRT, which is usually the heap limit, or status=9/KILL and oom-kill, which point to the kernel or MemoryMax. Nightly jobs that load a whole table into memory are the usual cause.

Read next

All VPS pages

This page in other languages: Azərbaycanca · Русский

Servers in Baku, prices in manat

Create an account, top up your balance and order the plan you need.