DEV Community

TateLyman
TateLyman

Posted on

systemd for Node.js Developers — Auto-Restart, Logging, and 24/7 Uptime

Why systemd?

PM2, forever, and nodemon are great for development. But for production on a Linux VM, systemd is already there and does everything you need.

The Service File

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

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/my-app
ExecStart=/usr/bin/node app.js
Restart=always
RestartSec=5
Environment=NODE_ENV=production
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

Key Features

Auto-Restart

Restart=always + RestartSec=5 means if your app crashes, it restarts in 5 seconds.

Logging

journalctl -u myapp -f        # Live logs
journalctl -u myapp --since today  # Today's logs
journalctl -u myapp -n 100    # Last 100 lines
Enter fullscreen mode Exit fullscreen mode

No log rotation config needed — journald handles it.

Commands

sudo systemctl start myapp    # Start
sudo systemctl stop myapp     # Stop
sudo systemctl restart myapp  # Restart
sudo systemctl status myapp   # Check status
sudo systemctl enable myapp   # Start on boot
Enter fullscreen mode Exit fullscreen mode

vs PM2

Feature systemd PM2
Auto-restart Yes Yes
Logging journald pm2 logs
Start on boot Yes (enable) Yes (startup)
Process list systemctl list-units pm2 list
Memory 0 overhead ~30MB
Install required No (built in) Yes (npm)

Production Setup

I run a 4,500-line trading bot on Oracle Cloud free tier using systemd. Been up for months with zero manual intervention.

Deploy guide: dev.to/tatelyman/deploy-any-nodejs-app-247-for-free-on-oracle-cloud

Top comments (0)