How to Deploy a Go App to a VPS with systemd

Deploy a Go app to a VPS by building a binary, transferring it, and configuring a systemd service unit for automatic management.

Compile your Go binary for the target architecture, transfer it to the VPS, and configure a systemd service unit to run it as a background process.

  1. Build the binary for the VPS architecture (e.g., linux/amd64) from your local machine. GOOS=linux GOARCH=amd64 go build -o myapp main.go
  2. Transfer the compiled binary to your VPS using SCP. scp myapp user@your-vps-ip:/opt/myapp/myapp
  3. Create a systemd service file to define how the application should run. sudo nano /etc/systemd/system/myapp.service
  4. Paste the service configuration into the file, replacing paths and user details.
    [Unit]
    Description=My Go Application
    After=network.target
    
    [Service]
    User=ubuntu
    WorkingDirectory=/opt/myapp
    ExecStart=/opt/myapp/myapp
    Restart=on-failure
    Environment=PORT=8080
    
    [Install]
    WantedBy=multi-user.target
    
  5. Reload systemd to recognize the new service file. sudo systemctl daemon-reload
  6. Enable the service to start on boot and start it immediately. sudo systemctl enable myapp && sudo systemctl start myapp
  7. Verify the service is running and check its status. sudo systemctl status myapp