Linux β€’ Web Apps & APIs

How to Create a Systemd Service for Node.js (Express, NestJS, Next.js)

Running Node.js directly with node server.js in production is risky if the process crashes. Configuring a systemd service guarantees that your Node.js application starts automatically on server boot, restarts upon unhandled exceptions, and streams logs cleanly to journalctl.

/etc/systemd/system/node-app.service
[Unit]
Description=Node.js Production Application
Documentation=https://nodejs.org
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/my-node-app
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=node-app
Environment=NODE_ENV=production PORT=3000
# Allow binding to privileged ports (<1024) if needed:
# AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
Customize:
User:
WorkingDir:
ExecStart:

Systemctl Lifecycle & Journalctl Monitoring

sudo systemctl daemon-reloadReload systemd manager configuration after adding or editing unit file
sudo systemctl enable --now node-appEnable service to start on boot AND start it immediately
sudo systemctl status node-appInspect active state, PID, memory consumption, and recent logs
sudo journalctl -u node-app -fStream real-time live application stdout/stderr logs

Linux & Systemd Production Best Practices

  • Always use absolute paths for both ExecStart and WorkingDirectory (e.g. `/usr/bin/node`, not just `node`). Find path with `which node`.
  • If using NVM (Node Version Manager), `node` is not in standard paths. Either install Node globally via NodeSource or symlink: `sudo ln -s $(which node) /usr/local/bin/node`.
  • For Next.js standalone servers, set WorkingDirectory to the standalone root and ExecStart to `/usr/bin/node server.js`.

Frequently Asked Questions About Node.js Systemd Service

Frequently Asked Questions

Frequently Asked Questions

Everything you need to know regarding specifications, syntax, and security best practices.

Systemd is the native Linux init system baked into the kernel space. It has zero additional memory overhead, boots before any user session, manages OS cgroups directly, and cannot crash like a userspace daemon.