Run a Go Binary as a Daemon under systemd
We want to run our Go program as a daemon on Linux, under systemd. Specifically, we want it to:
- start at the right time (e.g. after networking comes up)
- restart if it dies
- log STDOUT and STDERR
First, a little Go program for testing:
// stdout-stderr-test-daemon.go
package main
import (
"fmt"
"log"
"os"
"time"
)
func main() {
stderr := log.New(os.Stderr, "", 0)
for {
fmt.Println("Hello, STDOUT")
stderr.Println("Hello, STDERR")
time.Sleep(time.Millisecond * 15000)
}
}
Build and install the binary:
$ go build stdout-stderr-test-daemon.go
# cp stdout-stderr-test-daemon /usr/local/bin/
Here’s our systemd unit file, /etc/systemd/system/stdout-stderr-test-daemon.service
:
[Unit]
Description=Tests systemd to daemonize a Go binary
Documentation=https://paulgorman.org/technical/blog/20171121184114.html
Wants=network.target
After=network.target
[Service]
Type=simple
DynamicUser=yes
ExecStart=/usr/local/bin/stdout-stderr-test-daemon
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
See systemd.unit(5)
, systemd.service(5)
, and systemd.exec(5)
for unit file documentation.
Start our service, and watch it log:
# systemctl daemon-reload
# systemctl start stdout-stderr-test-daemon
# journalctl -u stdout-stderr-test-daemon
# journalctl -f -u stdout-stderr-test-daemon
To start the service at boot:
# systemctl enable stdout-stderr-test-daemon
#golang #systemd