Running Go app as a Service on Ubuntu
I recently wrote a simple Go app as the backend for my Singapore carpark availability page. So to keep this page running, I ran the Go app as a service on Ubuntu. Thankfully, this is pretty easy to set up.
Setting up Go app as a Service on Ubuntu
On Ubuntu, you set up a service using systemd. I’m not going into the details of systemd here but till get straight into what you need to do.
The first step is to create the new .service file. You can name it anything you like.
sudo nano /lib/systemd/system/go_app.service
Copy and paste the following configuration into the file. Edit the description as you like. It would be displayed when you check the status of the service.
The location of the go app binary goes to the ExecStart configuration. In the example below, the executable binary is located at /opt/appDir/go_app. You will also need to ensure the WorkingDirectory config is set especially if its dependant on any external files.
[Unit] Description=My example go application [Service] Type=simple Restart=always RestartSec=5s WorkingDirectory=/opt/appDir ExecStart=/opt/appDir/go_app [Install] WantedBy=multi-user.target
Remember to give the go app binary executable permissions. You can do so using the following command
sudo chmod +x /opt/appDir/go_app
Enabling the service
Now that you have the .service file created, you can use systemctl to enable, start, stop and restart the service.
In order to auto start the service after booting up, you have to remember to first enable the service.
sudo systemctl enable go_app
Then you can start, stop and check the status of the service just as how you would normally do it with systemctl.
sudo systemctl start go_app sudo systemctl status go_app
That’s it! The quick and simple steps to set up a go app to run as a service on Ubuntu. If you want to also set up the logging of the go app to be written to /var/log/go-app, just do a search online on how to configure the .service file to do so. There are plenty of guides out there on that.
Also check out
A quick checklist guide on how to upgrade Ubuntu 18.04 to 20.04 for servers running WordPress on Apache 2, MySQL and PHP using php-fpm.