DEV3 Technologies home

DEV3 Developer Forum

How do I run a Node.js app as a systemd service that starts on boot and restarts on crash?

DevOps helpSolved0 views
dev3 ·

I start my app with npm start in an SSH session and it dies when I disconnect. I would rather not install PM2. How do I make it a proper systemd service?

#systemd#nodejs#linux

0

1 reply

dev3 · Accepted answer

Create a unit file. Systemd handles start on boot, restart on failure, logging and resource limits.

/etc/systemd/system/myapp.service:

[Unit]
Description=My Node app
After=network.target

[Service]
Type=simple
User=deploy
WorkingDirectory=/var/www/myapp
EnvironmentFile=/var/www/myapp/.env
Environment=NODE_ENV=production
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5
# Hardening (optional)
NoNewPrivileges=true
ProtectSystem=full

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
journalctl -u myapp -f

Details

  • Use the absolute path to node (which node). If you use nvm, the path lives in the user's home, and systemd will not load shell profiles. Install Node system-wide or point to the nvm binary path explicitly.
  • EnvironmentFile takes KEY=value lines without export and without shell quoting tricks.
  • Do not run as root; create a dedicated user.
  • Restart=on-failure restarts on crashes; always also restarts after clean exits.
  • After editing the unit, run daemon-reload before restarting.
  • Logs go to the journal; view with journalctl -u myapp --since "1 hour ago".

Put Nginx in front as a reverse proxy to http://127.0.0.1:3000 and keep the app bound to localhost so only Nginx is public.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.