Application Hosting12 min read•Updated November 2026

How to Deploy a Go Web Service on a Linux VPS

Quick answer

Build a static Linux binary with CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build, copy it to the VPS, and run it under a systemd service as a dedicated user, listening on 127.0.0.1. Add server timeouts and graceful shutdown on SIGTERM in your code, put Nginx in front for HTTPS, and deploy each version into its own directory so a rollback is just a symlink change and a restart.

Go is one of the easiest languages to deploy. The compiler produces a single binary with no runtime to install, no virtual environment and no dependency folder on the server. That simplicity makes it tempting to just copy the file and run it in a tmux session, but a production service still needs supervision, a non-root user, timeouts, graceful shutdown and TLS. This guide adds those pieces with minimal moving parts.

Step 1: Build a Static Binary

Compile on your laptop or in CI, not on the server. For a typical x86-64 VPS:

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
  go build -trimpath -ldflags="-s -w -X main.version=$(git describe --tags)" \
  -o build/api ./cmd/api
  • CGO_ENABLED=0 produces a fully static binary that does not depend on the server's C library version. If you need cgo (for example some SQLite drivers), build on the same OS release as the server or use a pure-Go alternative.
  • -trimpath removes local file paths from the binary; -s -w strips debug symbols to shrink it.
  • The -X main.version=... flag stamps the version so you can expose it on a health endpoint.

Check the server's architecture with uname -m: x86_64 means GOARCH=amd64, aarch64 means arm64.

Step 2: Make the Service Production-Ready in Code

Two things belong in your Go code rather than in server configuration: timeouts and graceful shutdown. The default http.Server has no timeouts, which lets slow or malicious clients hold connections open indefinitely.

package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var version = "dev"

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok " + version))
	})

	addr := os.Getenv("LISTEN_ADDR") // e.g. 127.0.0.1:8080
	srv := &http.Server{
		Addr:              addr,
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %v", err)
		}
	}()
	log.Printf("listening on %s (version %s)", addr, version)

	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Printf("graceful shutdown failed: %v", err)
	}
}

When systemd stops or restarts the service it sends SIGTERM. Shutdown stops accepting new connections and waits for in-flight requests to finish, so deploys do not cut off users mid-request. Log to standard output; systemd's journal collects it.

Step 3: Prepare the Server

sudo adduser --system --group --home /opt/api api
sudo mkdir -p /opt/api/releases
sudo chown -R api:api /opt/api
sudo tee /opt/api/.env >/dev/null <<'EOF'
LISTEN_ADDR=127.0.0.1:8080
DATABASE_URL=postgres://api:change-me@127.0.0.1:5432/api?sslmode=disable
EOF
sudo chown api:api /opt/api/.env && sudo chmod 600 /opt/api/.env

Step 4: Upload a Release

Each version goes into its own directory, and a current symlink points at the live one:

REL=$(date +%Y%m%d%H%M%S)
scp build/api deploy@server:/tmp/api-$REL
ssh deploy@server "sudo install -o api -g api -m 0755 -D /tmp/api-$REL /opt/api/releases/$REL/api \
  && sudo ln -sfn /opt/api/releases/$REL /opt/api/current \
  && sudo systemctl restart api"

Rolling back is the same command with the previous release directory. Keep the last few releases and delete older ones.

Step 5: Run It with systemd

Create /etc/systemd/system/api.service:

[Unit]
Description=Go API
After=network-online.target
Wants=network-online.target

[Service]
User=api
Group=api
EnvironmentFile=/opt/api/.env
ExecStart=/opt/api/current/api
Restart=on-failure
RestartSec=2
TimeoutStopSec=30
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/opt/api/data
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
sudo mkdir -p /opt/api/data && sudo chown api:api /opt/api/data
sudo systemctl daemon-reload
sudo systemctl enable --now api
curl -s http://127.0.0.1:8080/health
journalctl -u api -f

TimeoutStopSec must be longer than the shutdown timeout in your code, otherwise systemd kills the process before it finishes draining requests. ProtectSystem=strict makes the filesystem read-only for the service except the paths you list, which limits damage if the service is ever compromised. Raise LimitNOFILE if the service holds many concurrent connections.

A Go program only needs privileges to bind ports below 1024. Listening on 127.0.0.1:8080 behind Nginx avoids that entirely.

Step 6: Nginx and HTTPS

server {
    listen 80;
    server_name api.example.com;
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d api.example.com

Read the client IP from X-Real-IP only when the request comes from 127.0.0.1; never trust forwarded headers from arbitrary sources. Go can also terminate TLS itself (for example with autocert), but a reverse proxy makes it easy to host several services on one VPS, as shown in our multiple-apps guide.

Performance Notes

  • Cores: Go schedules goroutines across all available CPU cores (GOMAXPROCS defaults to the number of CPUs), so more vCores directly help CPU-bound work.
  • Memory: set GOMEMLIMIT (for example GOMEMLIMIT=1500MiB) when the service shares a server with a database, so the garbage collector works harder before the process approaches the limit.
  • Database pools: configure SetMaxOpenConns and SetMaxIdleConns on database/sql; unlimited connections can overwhelm PostgreSQL.
  • Profiling: expose net/http/pprof only on a localhost-only listener, never on the public mux.

SkyRainCloud Plans for This Workload

Go services are compiled and memory-efficient, so even busy APIs often fit the 2 vCore / 8 GB plans alongside their database. Go uses every core automatically, so CPU-heavy services scale well on the 4–16 vCore AMD EPYC tiers.

AMD EPYC 7C13 VPS

Dedicated KVM vCores on AMD EPYC 7C13 (up to 3.70 GHz) with DDR4 ECC memory, NVMe SSD and an unmetered 1 Gbps port.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — AMD28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthWebsites, small APIs, bots, staging and VPN serversOrder
VPS 2 — AMD416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,299/monthWooCommerce, Node.js/Python backends, Docker Compose stacks, CI runnersOrder
VPS 3 — AMD832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,499/monthProduction databases, high-traffic sites, multi-container appsOrder
VPS 4 — AMD1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,899/monthLarge production workloads, SaaS platforms, analytics, in-memory cachesOrder

Intel Xeon Platinum 8269CY VPS

KVM VPS on Intel Xeon Platinum 8269CY (up to 3.80 GHz Turbo) with DDR4 ECC memory, NVMe SSD, full root access and an unmetered 1 Gbps port.

PlanvCoresRAMStorageNetworkPriceGood forBuy
VPS 1 — Intel28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹649/monthBusiness websites, small apps, scheduled jobs and botsOrder
VPS 2 — Intel416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,169/monthBusiness software, mid-size databases, several sites on one serverCheck stock
VPS 3 — Intel832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,249/monthERP/CRM stacks, heavier databases, multiple production appsCheck stock
VPS 4 — Intel1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,299/monthHigh-memory workloads and consolidated production serversCheck stock

Prices are monthly in INR as listed on the SkyRainCloud store (verified 2026-11-14). Stock and final pricing are shown on the product page at checkout.

Troubleshooting

SymptomCause and fix
exec format errorWrong GOARCH; rebuild for the server's architecture
Binary fails with a glibc version errorBuilt with cgo against a newer C library; use CGO_ENABLED=0 or build on the server's OS release
Service exits with "permission denied"Writes outside ReadWritePaths under ProtectSystem=strict; add the path
Requests cut off during deployNo graceful shutdown, or TimeoutStopSec shorter than the drain time
502 from NginxService not listening on the address in proxy_pass; check LISTEN_ADDR and journalctl -u api

Frequently Asked Questions

Do I need to install Go on the server?
No. Build the binary on your machine or in CI and copy only the compiled file. The server needs no Go toolchain.
Why use CGO_ENABLED=0?
It produces a static binary that does not depend on the server's C library, so it runs on any Linux release with the same CPU architecture. Use cgo only when a dependency requires it.
How do I run a Go program as a service on Linux?
Create a systemd unit with ExecStart pointing at the binary, a dedicated User, an EnvironmentFile for configuration and Restart=on-failure, then systemctl enable --now it.
Should a Go service sit behind Nginx?
Usually yes. Nginx handles TLS certificates, lets several services share ports 80/443, and adds request limits and logging. Go can serve TLS directly if it is the only service on the server.
How do I deploy Go updates without downtime?
Implement graceful shutdown, deploy into a new release directory, and restart. For true zero downtime run two instances behind an Nginx upstream and restart them one at a time.
What server timeouts should a Go HTTP server have?
At least ReadHeaderTimeout; typical values are 5s for headers, 15s read, 30s write and 60s idle. Adjust write timeouts for endpoints that stream large responses.
How much RAM does a Go API need?
Often tens of megabytes at idle and a few hundred under load, depending on caching and payload sizes. The database usually needs more memory than the Go service itself.
How do I roll back a bad Go release?
Point the current symlink back to the previous release directory and restart the service. Keeping releases in separate directories makes this instant.
Where do Go service logs go?
Log to standard output and standard error; systemd stores them in the journal. Read them with journalctl -u api.
Which SkyRainCloud plan suits a Go service?
Most Go APIs with a database run well on the 2 vCore / 8 GB plan. Choose more vCores for CPU-heavy processing, since Go uses all cores automatically; AMD EPYC tiers offer up to 16 vCores.
Instant UPI • ₹649/mo
Fast KVM Cloud Provisioning