NewCode CLOUD — 20% off your first month on all cloud VPSClaim

How to Deploy a Go (Golang) API on Hong Kong VPS: Production Guide (2026)

· 5 min read

Go’s combination of fast compilation, small binary output, and excellent concurrency primitives makes it a popular choice for API backends that need to handle high request volumes efficiently. Like Rust, a compiled Go binary deployed on a Hong Kong VPS with CN2 GIA routing starts in milliseconds, uses a fraction of the RAM that Node.js or Python runtimes consume, and delivers Asian API clients low-latency responses via the premium AS4809 backbone.


Why Go on a VPS?

  • Single binary deployment — go build produces a statically linked executable. Copy it to your VPS and run it — no runtime, no package manager, no version conflicts
  • Built-in concurrency — goroutines handle thousands of concurrent connections with a tiny memory footprint versus thread-per-request models
  • Standard library — Go’s net/http is production-ready without a framework; add Chi or Gin for routing if needed
  • Fast cold start — Go binaries start in under 100ms, making systemd restarts and deployments near-instant

Step 1: Install Go on the Build Machine

# Install on your VPS or a local Linux build machine
GO_VERSION="1.22.5"
wget https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz
tar -C /usr/local -xzf go${GO_VERSION}.linux-amd64.tar.gz

echo 'export PATH=$PATH:/usr/local/go/bin' >> /etc/profile.d/go.sh
source /etc/profile.d/go.sh

go version  # Should show: go version go1.22.5 linux/amd64

Step 2: Project Structure and Dependencies

mkdir -p /tmp/hk-go-api && cd /tmp/hk-go-api
go mod init github.com/yourorg/hk-api

go get github.com/go-chi/chi/v5
go get github.com/go-chi/chi/v5/middleware
go get github.com/jackc/pgx/v5
go get github.com/redis/go-redis/v9
go get github.com/golang-jwt/jwt/v5
go get golang.org/x/crypto/bcrypt
go get github.com/joho/godotenv

Main Application

<code">cat > main.go << 'EOF'
package main

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

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
    "github.com/joho/godotenv"
)

func main() {
    // Load environment variables
    if err := godotenv.Load(); err != nil {
        log.Println("No .env file found, using environment variables")
    }

    // Initialise database pool
    db, err := NewDB(os.Getenv("DATABASE_URL"))
    if err != nil {
        log.Fatalf("Failed to connect to database: %v", err)
    }
    defer db.Close()

    // Initialise Redis client
    rdb := NewRedis(os.Getenv("REDIS_URL"))
    defer rdb.Close()

    // Build router
    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)
    r.Use(middleware.RealIP)
    r.Use(middleware.Timeout(30 * time.Second))
    r.Use(corsMiddleware)

    // Public routes
    r.Get("/health", healthHandler(db, rdb))
    r.Post("/api/v1/auth/login", loginHandler(db, rdb))
    r.Post("/api/v1/auth/register", registerHandler(db))

    // Protected routes
    r.Group(func(r chi.Router) {
        r.Use(jwtMiddleware)
        r.Get("/api/v1/me", getMeHandler(db))
        r.Get("/api/v1/products", listProductsHandler(db, rdb))
        r.Post("/api/v1/products", createProductHandler(db, rdb))
    })

    addr := os.Getenv("BIND_ADDR")
    if addr == "" {
        addr = "127.0.0.1:8080"
    }

    srv := &http.Server{
        Addr:         addr,
        Handler:      r,
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 30 * time.Second,
        IdleTimeout:  60 * time.Second,
    }

    // Graceful shutdown
    go func() {
        log.Printf("Server starting on %s", addr)
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Server error: %v", err)
        }
    }()

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit

    log.Println("Shutting down gracefully...")
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    srv.Shutdown(ctx)
    log.Println("Server stopped")
}
EOF

Database Connection Pool

<code">cat > db.go << 'EOF'
package main

import (
    "context"
    "fmt"

    "github.com/jackc/pgx/v5/pgxpool"
)

func NewDB(databaseURL string) (*pgxpool.Pool, error) {
    config, err := pgxpool.ParseConfig(databaseURL)
    if err != nil {
        return nil, fmt.Errorf("parsing database URL: %w", err)
    }

    config.MaxConns = 20
    config.MinConns = 2

    pool, err := pgxpool.NewWithConfig(context.Background(), config)
    if err != nil {
        return nil, fmt.Errorf("creating pool: %w", err)
    }

    if err := pool.Ping(context.Background()); err != nil {
        return nil, fmt.Errorf("pinging database: %w", err)
    }

    return pool, nil
}
EOF

Rate Limiting Middleware

<code">cat > middleware.go << 'EOF' package main import ( "context" "net/http" "time" "github.com/redis/go-redis/v9" ) func rateLimitMiddleware(rdb *redis.Client, limit int, window time.Duration) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() key := "ratelimit:" + r.RemoteAddr count, err := rdb.Incr(ctx, key).Result() if err != nil { next.ServeHTTP(w, r) return } if count == 1 { rdb.Expire(ctx, key, window) } if count > int64(limit) {
                http.Error(w, `{"error":"rate limit exceeded"}`, http.StatusTooManyRequests)
                return
            }
            
            w.Header().Set("X-RateLimit-Remaining", 
                fmt.Sprintf("%d", limit-int(count)))
            next.ServeHTTP(w, r)
        })
    }
}
EOF

Step 3: Build the Production Binary

<code"># Build with optimisations
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
    go build -ldflags="-w -s" -o hk-api .

# Check binary size — typically 5–15 MB
ls -lh hk-api

# Cross-compile from macOS/Windows to Linux
GOOS=linux GOARCH=amd64 go build -o hk-api-linux .

The -w -s flags strip debug symbols and symbol tables, reducing binary size by 30–50%. CGO_ENABLED=0 produces a fully static binary with zero runtime dependencies.


Step 4: Deploy to VPS

<code"># On the VPS — create app user and directories
useradd -r -s /bin/false goapi
mkdir -p /opt/hk-api
chown goapi:goapi /opt/hk-api

# Copy binary
scp hk-api root@YOUR_VPS_IP:/opt/hk-api/
chmod +x /opt/hk-api/hk-api

# Create environment file
cat > /opt/hk-api/.env << 'EOF'
DATABASE_URL=postgresql://apiuser:Password123!@localhost/api_db?pool_max_conns=20
REDIS_URL=redis://:RedisPassword@localhost:6379/0
JWT_SECRET=GENERATE_64_CHAR_SECRET_HERE
BIND_ADDR=127.0.0.1:8080
EOF
chmod 600 /opt/hk-api/.env

Systemd Service

<code">cat > /etc/systemd/system/hk-api.service << 'EOF'
[Unit]
Description=HK VPS Go API
After=network.target postgresql.service redis.service

[Service]
Type=simple
User=goapi
WorkingDirectory=/opt/hk-api
EnvironmentFile=/opt/hk-api/.env
ExecStart=/opt/hk-api/hk-api
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=3
# Memory and CPU limits
MemoryMax=512M
CPUQuota=200%    # Allow up to 2 CPU cores
# Security hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/opt/hk-api

[Install]
WantedBy=multi-user.target
EOF

systemctl enable --now hk-api
systemctl status hk-api

# Test
curl http://127.0.0.1:8080/health

Step 5: Nginx Configuration

<code">cat > /etc/nginx/sites-available/go-api << 'EOF'
upstream go_api {
    server 127.0.0.1:8080;
    keepalive 32;
}

server {
    listen 443 ssl http2;
    server_name api.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.yourdomain.com/privkey.pem;

    client_max_body_size 10m;
    server_tokens off;

    location /api/ {
        proxy_pass http://go_api;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;
        proxy_read_timeout 30s;
    }

    location /health {
        proxy_pass http://go_api;
        access_log off;
    }
}
EOF

ln -s /etc/nginx/sites-available/go-api /etc/nginx/sites-enabled/
certbot --nginx -d api.yourdomain.com
nginx -t && systemctl reload nginx

Step 6: Zero-Downtime Deployment

Go supports graceful shutdown natively (as shown in main.go above). Systemd’s ExecReload=/bin/kill -HUP triggers a graceful reload without dropping in-flight requests:

<code"># GitHub Actions deployment workflow:
# Build binary → SCP to VPS → systemctl restart (graceful)

# On VPS — atomic binary swap
OLD_BINARY="/opt/hk-api/hk-api"
NEW_BINARY="/tmp/hk-api-new"

scp hk-api root@VPS_IP:$NEW_BINARY
ssh root@VPS_IP "
  mv $OLD_BINARY ${OLD_BINARY}.bak
  mv $NEW_BINARY $OLD_BINARY
  chmod +x $OLD_BINARY
  systemctl restart hk-api
  sleep 3
  curl -sf http://127.0.0.1:8080/health || {
    mv ${OLD_BINARY}.bak $OLD_BINARY
    systemctl restart hk-api
    echo 'ROLLBACK executed'
    exit 1
  }
"

Step 7: Structured Logging with slog

<code">// Go 1.21+ includes slog — structured logging in the standard library
import "log/slog"

// Set up JSON logging (production)
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))
slog.SetDefault(logger)

// Log structured events
slog.Info("request handled",
    slog.String("method", r.Method),
    slog.String("path", r.URL.Path),
    slog.Int("status", statusCode),
    slog.Duration("latency", time.Since(start)),
    slog.String("ip", r.RemoteAddr),
)

Performance Benchmarks

Metric Go API (4 vCPU HK VPS) Node.js API (same VPS)
Requests/sec (simple GET) 40,000–80,000 15,000–25,000
P99 latency (no DB) 2–5ms 5–15ms
RAM at 1,000 concurrent 30–60 MB 200–400 MB
Binary size 8–15 MB N/A (requires Node.js runtime)
Startup time <100ms 500ms–2s

Conclusion

A Go API deployed as a static binary on a Hong Kong VPS combines the performance characteristics (low memory, high concurrency, fast startup) that make Go popular for cloud-native services, with the operational simplicity of a single file on a Linux server. CN2 GIA routing delivers API responses to mainland Chinese clients at 30–55ms — matching or beating what managed cloud API services deliver from the same region at a fraction of the cost.

Deploy your Go API: Browse Server.HK Hong Kong VPS plans — a 2 GB plan handles most Go API workloads; the low memory footprint leaves room for PostgreSQL and Redis alongside.

Related articles

More in VPS & ServersServer setup guides