Prerequisites
Before configuring auto-restart, make sure you have:
- SSH access to your VPS
- Root or sudo privileges
Method 1: Modify Existing Service File
Connect to your VPS:
ssh hxroot@YOUR_SERVER_IP -p 22
Edit the service override:
sudo systemctl edit nginx
Add the following:
[Service]
Restart=on-failure
RestartSec=5s
Save and exit. Then reload:
sudo systemctl daemon-reload
Restart the service:
sudo systemctl restart nginx
Restart Policies Explained
- no – Never restart
- on-success – Restart only if exit code 0
- on-failure – Restart on non-zero exit, timeout, or crash (recommended)
- always – Always restart (even if stopped manually)
- on-abnormal – Restart on signal, timeout, or watchdog
Additional Useful Options
[Service]
Restart=on-failure
RestartSec=10s
StartLimitInterval=200s
StartLimitBurst=5
These settings limit restart attempts to 5 times within 200 seconds (prevents infinite restart loops).
Method 2: Create a Complete Service File
sudo nano /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
User=www-data
ExecStart=/usr/bin/node /opt/myapp/app.js
Restart=on-failure
RestartSec=10
StartLimitInterval=300
StartLimitBurst=5
[Install]
WantedBy=multi-user.target
Test Auto-Restart
Find PID of the service:
systemctl status nginx | grep PID
Kill the process:
sudo kill -9 PID
Wait a few seconds, then check:
systemctl status nginx
The service should have restarted automatically.
View Restart Count
systemctl show nginx -p NRestarts
Disable Auto-Restart for a Service
sudo systemctl edit nginx
Set:
[Service]
Restart=no
Then:
sudo systemctl daemon-reload
✅ Auto-restart configured. Your services will recover automatically from crashes.