On Ubuntu, you can use the systemd service manager to restart a service automatically if it fails. To do this, you will need to edit the service's unit file and add a Restart directive.
Here is an example of how you can edit the unit file for a service named myservice to restart the service automatically if it fails:
Open the terminal and enter the following command to open the unit file for the service in a text editor:
sudo nano /etc/systemd/system/myservice.service
Add the Restart directive to the [Service] section of the unit file. For example:
[Service]
...
Restart=on-failure
Save the changes to the unit file and exit the text editor.
Reload the systemd manager's configuration and restart the service using the following commands:
sudo systemctl daemon-reload
sudo systemctl restart myservice
Now, if the myservice service fails, systemd will automatically restart it. You can use the systemctl show myservice command to view the current status and settings for the service.