Run a Node app as a systemd service

Start on boot, restart on crash, logs in journalctl. No pm2 needed.

SNP 104 #64B Filed cmd node systemd linux

/etc/systemd/system/myapp.service:

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

[Service]
Type=simple
User=deploy
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
EnvironmentFile=-/var/www/myapp/.env

[Install]
WantedBy=multi-user.target

Then:

shell
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
journalctl -fu myapp

Run daemon-reload again every time you edit the file. The - before the EnvironmentFile path means "don't fail if it's missing". which node tells you the path to put in ExecStart; it's often under /usr/local/bin or in nvm's folder.