The systemd Unit That Keeps My Go Service Alive
A Go binary does not keep itself alive. The systemd unit is what turns "a process" into "a service that survives." Here is the unit I actually run, and why each line is there.
The unit
[Unit]
Description=myapp
After=network.target
[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/myapp
EnvironmentFile=/opt/myapp/.env
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ReadWritePaths=/opt/myapp/data
[Install]
WantedBy=multi-user.target
Why each line
Restart=on-failure+RestartSec=3— most crashes become a 3-second blip instead of an outage. This is the single highest-value line in the file.User=myapp/Group=myapp— never run a network service as root. A dedicated system user contains the blast radius.WorkingDirectory=/opt/myapp— the app finds its data files relative to a known place. This one bug cost me an hour once.EnvironmentFile=/opt/myapp/.env— secrets live in a root-owned file, not in the unit and not in git.NoNewPrivileges=true/PrivateTmp=true/ProtectSystem=full/ReadWritePaths=— hardening: the process cannot escalate, write to the rest of the filesystem, or share temp. The app can only write where it is supposed to.
Deploying a new version
go build -o myapp-linux ./cmd/myapp
scp myapp-linux user@server:/opt/myapp/myapp
sudo systemctl restart myapp
systemctl status myapp --no-pager
Because the binary is static, restart is fast and boring. Rollback is keeping the old binary.
What it costs
A unit file like this is what turns a cheap VPS into a reliable home for a service. If you are comparing that VPS against managed hosting, the calculator below shows the real difference in running costs.
Comments (0)
No comments yet.