How to fix mysql and nginx stopping automatically on VPS

For MySQL:

  1. Open the MySQL autorestart service

sudo nano /etc/systemd/system/mysql-autorestart.service

  1. Update the [Service] section as follows

[Unit]
Description=MySQL Auto Restart Service
After=network.target

[Service]
ExecStart=/bin/systemctl start mysql
Restart=always
RestartSec=3

[Install]
WantedBy=default.target

  1. Save the file and exit the text editor.
  2. Reload

sudo systemctl daemon-reload

  1. Enable and start the service:

sudo systemctl enable --now mysql-autorestart.service

For Nginx:

  1. Open the Nginx autorestart service
    sudo nano /etc/systemd/system/nginx-autorestart.service

  1. Update the [Service] section

[Unit]

Description=Nginx Auto Restart Service

After=network.target

[Service]

ExecStart=/bin/systemctl start nginx

Restart=always

RestartSec=3

[Install]

WantedBy=default.target

  1. Save the file and exit the text editor.
  2. Reload systems

sudo systemctl daemon-reload

  1. Enable and start the service

sudo systemctl enable --now nginx-autorestart.service

After making these changes, the services should automatically restart if they stop unexpectedly. Check the status of the services and their logs for any errors:

sudo systemctl status mysql-autorestart.service
sudo systemctl status nginx-autorestart.service
journalctl -xe