Setting up a golang website to autorun on Ubuntu using systemd
Here is how to set up a website to auto-launch and restart on failure on Ubuntu using systemd. I’m using a simple site written in Go and compiled into an executable called gosite – I got sample Go code from Jeffrey Bolle’s page.
Simple golang website code
package main import( "net/http" "log" "os" ) const resp = `Simple Web App Hello World!` func handler(w http.ResponseWriter, r *http.Request) { w.Write([]byte(resp)) } func main() { http.HandleFunc("/", handler) err := http.ListenAndServe(":8080", nil) if err != nil { log.Println(err) os.Exit(1) } }
Setting up systemd
Once the code is ready and tested, lets move on to setting up systemd.
Create and open a file in the /lib/systemd/system folder:
vim /lib/systemd/system/gosite.service
Edit the file with your parameters to match the contents below:
[Unit] Description=A simple go website ConditionPathExists=/home/user/bin/gosite [Service] Restart=always RestartSec=3 ExecStart=/home/user/bin/gosite [Install] WantedBy=multi-user.target
Enable the service using systemctl:
[email protected]:/home/user# systemctl enable gosite.service Created symlink from /etc/systemd/system/multi-user.target.wants/gosite.service to /lib/systemd/system/gosite.service.
Start the service:
service gosite start
Observe the service is running:
[email protected]:/home/user# ps aux | grep gosite root 27413 0.0 0.2 827776 5012 ? Ssl 15:50 0:00 /home/user/bin/gosite
Leave a Reply