NEWUse coupon code SMX20 to get 20% OFF your first billing cycle on any game server or VPS!Explore Store

VPS HOSTING

How to Deploy a Go Web Service on a Linux VPS

Ship a Go API to a Linux VPS: build a static binary, run it under systemd with a dedicated user, add graceful shutdown and timeouts, proxy through Nginx with HTTPS and deploy with instant rollback.

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.

ServoMix 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
SMX vPro XS (AMD EPYC)28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹420/moWebsites, small APIs, bots, staging and VPN serversOrder
SMX vPro S (AMD EPYC)416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹560/moWooCommerce, Node.js/Python backends, Docker Compose stacks, CI runnersOrder
SMX vPro M (AMD EPYC)832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹840/moProduction databases, high-traffic sites, multi-container appsOrder
SMX vPro L (AMD EPYC)1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹1,120/moLarge 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
SMX vCore XS (Intel Xeon)28 GB DDR4 ECC40 GB NVMe SSD1 Gbps, unmetered₹270/moBusiness websites, small apps, scheduled jobs and botsOrder
SMX vCore S (Intel Xeon)416 GB DDR4 ECC80 GB NVMe SSD1 Gbps, unmetered₹1,169/monthBusiness software, mid-size databases, several sites on one serverCheck stock
SMX vCore M (Intel Xeon)832 GB DDR4 ECC150 GB NVMe SSD1 Gbps, unmetered₹2,249/monthERP/CRM stacks, heavier databases, multiple production appsCheck stock
SMX vCore L (Intel Xeon)1664 GB DDR4 ECC250 GB NVMe SSD1 Gbps, unmetered₹4,248/monthHigh-memory workloads and consolidated production serversCheck stock

Prices are monthly in INR as listed on the ServoMix 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 ServoMix 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.

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 ServoMix 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.

Was this article helpful?

Your feedback helps us continuously improve ServoMix guides.

Share this article

Know someone who may find this guide useful?

How to Deploy a Go Web Service on a Linux VPS | ServoMix