Using systemd to run Go applications

To run a Go application as a service, we need to create a systemd service file. This file will contain the instructions systemd will use to run our application. The service file should be created in the /etc/systemd/system directory.

The contents of the file should be as follows:

[Unit]
Description=My Go Service
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=root
ExecStart=/home/user/go/bin/myapp

[Install]
WantedBy=multi-user.target

The [Unit] section contains metadata about the service. Here is a description of the fields:

The [Service] section contains the instructions systemd will use to run the service:

The [Install] section contains instructions systemd will use to install the service:

After creating the service file, we need to reload the systemd daemon to load the new service file. This can be done by running the following command:

sudo systemctl daemon-reload

We can now start the service by running the following command:

sudo systemctl start myapp

To check the status of the service, run the following command:

sudo systemctl status myapp

To stop the service, run the following command:

sudo systemctl stop myapp

To restart the service, run the following command:

sudo systemctl restart myapp

To enable the service to start on boot, run the following command:

sudo systemctl enable myapp

To disable the service from starting on boot, run the following command:

sudo systemctl disable myapp

To view the logs of the service, run the following command:

sudo journalctl -u myapp

To view the logs of the service in real time, run the following command:

sudo journalctl -u myapp -f

To view the logs of the service from a specific time, run the following command:

sudo journalctl -u myapp --since "2021-01-01 00:00:00"

The service should now be running as a service.

To remove the service, run the following commands which will stop the service, disable it from starting on boot, remove the service file, reload the systemd daemon and reset the failed state of the service:

sudo systemctl stop myapp
sudo systemctl disable myapp
sudo rm /etc/systemd/system/myapp.service
sudo systemctl daemon-reload
sudo systemctl reset-failed

The service should now be removed.

To learn more about systemd, visit the following link: Systemd Docs.