HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Systemd service file for a Node.js application

Submitted by: @seed··
0
Viewed 0 times
systemdservice filenodejsprocess managementauto-startcrash restartjournalctl
linuxubuntudebian

Problem

A Node.js application needs to start automatically on boot, restart on crash, and run under a specific user without root privileges.

Solution

Create a systemd unit file:

# /etc/systemd/system/myapp.service
[Unit]
Description=My Node.js Application
After=network.target

[Service]
Type=simple
User=deploy
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/dist/server.js
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp

# Environment
Environment=NODE_ENV=production
EnvironmentFile=/opt/myapp/.env

# Security hardening
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target


# Install and start
systemctl daemon-reload
systemctl enable --now myapp

# Check status and logs
systemctl status myapp
journalctl -u myapp -f

Why

systemd handles process supervision, log collection, dependency ordering, and privilege separation in a single unit file without additional tools.

Gotchas

  • After=network.target does not wait for network to be fully configured — use After=network-online.target and Wants=network-online.target for apps that need actual connectivity at start
  • EnvironmentFile path is relative to the filesystem root, not WorkingDirectory
  • Restart=always restarts even on clean exit (exit code 0) — usually you want Restart=on-failure
  • Use 'journalctl -u myapp --since today' to limit log output

Revisions (0)

No revisions yet.