VPS Tutorials
Deploy Go on a VPS: cross-compilation, systemd, Nginx and memory
Build a Linux Go artifact, deploy embedded or external assets, supervise it with systemd and serve HTTPS with Nginx. Tune GOMEMLIMIT, understand container CPU defaults, implement graceful shutdown and verify rollback.

A pure-Go application can be deployed as a single binary without installing the Go toolchain on the VPS. Compile locally or in CI, transfer the artifact, then supervise it. Static linking is conditional: CGO, external files, certificates and timezone data still need attention. Common failures include Exec format error, missing loaders or resources and memory pressure.
This Ubuntu 24.04 guide covers cross-compilation, assets, systemd, memory tuning, graceful shutdown, Nginx and recoverable releases. A restart-based deployment can briefly interrupt availability; continuous service requires an additional tested deployment arrangement.
Benefits:
- No Go compiler is needed on the runtime VPS.
- Compiled dependencies do not change when an upstream package updates; retain the artifact, lockfiles and build identity.
- Startup and memory can suit small machines, depending on the actual application.
- macOS or Windows can build for Linux when dependencies support the target.
Limits:
- Templates and frontend files require explicit embedding or deployment.
- CGO can introduce dynamic-loader and library requirements.
- A sensible memory budget helps, but cannot prevent every OOM.
- The application must implement graceful shutdown; the service manager cannot finish requests for it.
Example Linux build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build \
-trimpath \
-ldflags="-s -w -X main.version=$(git rev-parse --short HEAD)" \
-o dist/myapp ./cmd/myapp
CGO_ENABLED=0 disables CGO. For compatible pure-Go dependencies this avoids a C runtime dependency. CGO-enabled programs may depend on glibc and its loader; Ubuntu, Debian and musl-based Alpine are not automatically interchangeable. Inspect the resulting artifact rather than assuming static linking.
GOOS=linux GOARCH=amd64 selects the target platform:
| VPS architecture | GOARCH |
|---|---|
| x86_64 / amd64 | amd64 |
| ARM64 | arm64 |
Check the VPS using uname -m: x86_64 means amd64, aarch64 means arm64. See the ARM purchasing guide.
-trimpath removes local build paths and assists reproducibility. -s -w removes symbol/debug sections; the source's 20–30% reduction is illustrative, not guaranteed, and ordinary Go panic stack traces generally remain available. Keep an appropriate debug build when diagnosis needs it.
-X main.version=... sets a string variable to the commit identity:
var version = "dev"
func main() {
log.Printf("starting myapp version=%s", version)
// ...
}
Match the variable's actual package path and keep a clean source/lockfile record. When a dependency requires CGO, build in a compatible target environment or configure a suitable cross C toolchain, including musl when deliberately producing a compatible static build. CGO cross-compilation is possible with the right tooling; merely changing GOARCH is insufficient.
Ordinary binaries do not automatically include templates, CSS, images or frontend build output.
import (
"embed"
"html/template"
"net/http"
)
//go:embed templates/*.html static/*
var assets embed.FS
func main() {
tpl := template.Must(template.ParseFS(assets, "templates/*.html"))
http.Handle("/static/", http.FileServer(http.FS(assets)))
_ = tpl
http.ListenAndServe("127.0.0.1:3000", nil)
}
Embedding couples the assets to the binary, simplifying artifact rollback. With //go:embed:
../cannot traverse outside the permitted embed tree;- directory traversal normally excludes names beginning with
_or.; use//go:embed all:staticwhen deliberately including them.
Check build patterns and routes. Do not accidentally embed credentials or development files.
Frontend artifacts can be served by Nginx instead of Go http.FileServer. Performance depends on caching, filesystem and workload; it is not a universal speed guarantee.
| Choice | Embedded assets | External files with Nginx |
|---|---|---|
| Deployment | One coupled artifact | Coordinate binary and assets |
| Delivery | Go process | Proxy serves files directly |
| Frontend updates | Rebuild binary | Deploy versioned files |
| Binary size | Includes assets | Unchanged by external assets |
A practical pattern uses go:embed for templates and versioned external frontend files. Preserve the asset set used by the rollback release.
A foreground program suits Type=simple. Save /etc/systemd/system/myapp.service:
[Unit]
Description=Go App
After=network.target
[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/srv/app/current
EnvironmentFile=/srv/app/shared/.env
Environment=GOMEMLIMIT=400MiB
ExecStart=/srv/app/current/myapp
Restart=always
RestartSec=3
# 优雅退出:给 15 秒处理完在途请求
KillSignal=SIGTERM
TimeoutStopSec=15
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
# 资源与安全限制
MemoryMax=512M
LimitNOFILE=65535
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/app/shared
[Install]
WantedBy=multi-user.target
Before enabling, create appuser, /srv/app/releases and /srv/app/shared, install the executable with that account's ownership, prepare current and create the protected environment file. The deployment account needs limited service restart privileges.
WorkingDirectorymatters for./config.yamland./templates; absolute paths orgo:embedreduce working-directory mistakes.EnvironmentFilepoints toshared/.envso secrets survive release changes. systemd reads it; Go must still consume the intended variables.ProtectSystem=strictmakes most paths read-only. Declare actual upload/log/cache directories withReadWritePathsto avoidRead-only file system. Keep.envprotected against application writes rather than treating secrets as ordinary writable data.
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
GOGC=100 is a garbage-collection growth target, not a rule that memory is collected only after total RSS doubles. GOMEMLIMIT, introduced in Go 1.19, provides a soft runtime-managed memory limit:
Environment=GOMEMLIMIT=400MiB
The source suggests a 20–30% margin below the process/cgroup budget, illustrated by MemoryMax=512M with GOMEMLIMIT=400MiB. Measure the margin: runtime-managed stacks and structures are already included in the Go limit; memory from CGO, direct mmap and some operating-system resources is outside it. A large live heap can exceed the soft limit, and an excessively low limit can cause heavy GC work.
The hard limit is still systemd MemoryMax or Docker --memory. Coordinate both and monitor OOM events.
The source pprof snippet is:
import _ "net/http/pprof"
go func() {
log.Println(http.ListenAndServe("127.0.0.1:6060", nil))
}()
Use an SSH tunnel for http://localhost:6060/debug/pprof/heap, with the debug listener bound only to 127.0.0.1. Use a separate debug ServeMux: importing pprof registers handlers on DefaultServeMux, and using that same mux for the application can expose debug routes through Nginx even when port 6060 is private. Profiles reveal sensitive runtime data; protect and remove unnecessary debug exposure.
Older runtimes could schedule for host CPU count despite a smaller container quota, requiring settings such as GOMAXPROCS=1. Go 1.25 added Linux cgroup-aware defaults and periodic adjustment of GOMAXPROCS.
Do not assume a one-CPU quota always gives a default of one: the container-aware calculation normally has a minimum of two unless logical CPU/affinity limits are lower, and fractional quota is rounded up. Language-version defaults and explicit overrides also matter. Evaluate whether an old manual GOMAXPROCS is still needed. GODEBUG=containermaxprocs=0 disables quota consideration; a manually set GOMAXPROCS also changes automatic behavior. Check Go 1.25 release documentation.
Go maintains the two newest release families. The source's September 2026 versions 1.27.1/1.26.8 and retirement of 1.25 are historical. The official release listing checked on 16 November 2026 shows 1.27.4 and 1.26.11. Build with a supported, patched toolchain, test, then redeploy; the already built binary does not receive security fixes on its own.
systemctl restart stops the old process with SIGTERM. Without signal handling, active requests can be interrupted. The application pattern is:
srv := &http.Server{
Addr: "127.0.0.1:3000",
Handler: mux,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("forced shutdown:", err)
}
log.Println("server exited")
srv.Shutdown(ctx)stops accepting new connections and waits for ordinary active HTTP requests.- Keep the application's shutdown deadline below
TimeoutStopSec; here 10 seconds fits within 15, but longer requests require a planned drain policy. - Handle
SIGTERM, not justSIGINT. http.Serverhas zero timeout defaults. Set suitableReadTimeoutandWriteTimeout, plus header/idle limits as appropriate; streaming responses need different deadlines.
Shutdown does not automatically close hijacked WebSockets or finish every background job. Track and drain those separately. An orderly shutdown helps requests already in progress, but a single-instance restart still has a listening gap.
Bind Go to 127.0.0.1:3000, with Nginx serving public HTTP/HTTPS:
upstream goapp {
server 127.0.0.1:3000;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name app.example.com;
client_max_body_size 20m;
access_log /var/log/nginx/app.access.log;
error_log /var/log/nginx/app.error.log warn;
location / {
proxy_pass http://goapp;
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;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
# WebSocket / SSE(Go 里很常见)
location /ws/ {
proxy_pass http://goapp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s;
proxy_buffering off;
}
}
sudo nginx -t && sudo systemctl reload nginx
Add HTTPS using Certbot after checking DNS and public 80/443, test renewal, or use the Caddy guide. Save the proxy file in a loaded Nginx configuration directory and check cloud/UFW rules.
Forward X-Forwarded-For, but remember r.RemoteAddr still identifies the directly connected proxy, often 127.0.0.1. Your framework must explicitly parse forwarded headers only from trusted proxies. Copying the header does not rewrite RemoteAddr automatically. The /ws/ example also needs matching forwarded protocol/client headers if it uses them; SSE does not require a WebSocket Upgrade header, but does need suitable buffering and timeout settings.
The original deployment script is:
#!/usr/bin/env bash
set -euo pipefail
HOST=deploy@your-vps
RELEASE=$(date +%Y%m%d-%H%M%S)
TARGET=/srv/app/releases/$RELEASE
# 1. 本地编译
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
-trimpath \
-ldflags="-s -w -X main.version=$(git rev-parse --short HEAD)" \
-o /tmp/myapp ./cmd/myapp
# 2. 传输
ssh "$HOST" "mkdir -p $TARGET"
scp /tmp/myapp "$HOST:$TARGET/myapp"
# 3. 切换并重启
ssh "$HOST" "chmod +x $TARGET/myapp && \
ln -sfn $TARGET /srv/app/current && \
sudo systemctl restart myapp"
# 4. 清理旧版本,保留最近 5 个
ssh "$HOST" "ls -1dt /srv/app/releases/* | tail -n +6 | xargs -r rm -rf"
Retain set -euo pipefail so failed builds do not switch current to a stale or missing artifact. Replace host/path placeholders, verify SSH host keys, record commit and checksum, and ensure runtime-readable ownership.
Before switching, save the old release target. After restart, verify the actual running version and both local and public health. On failure, restore the old target and restart again. Perform cleanup only after health succeeds, retaining the active and rollback releases; the source's automatic retention of five is not a rollback guarantee. For continuous availability, start a new instance on a separate private port, check readiness, switch the proxy, then drain the old instance. Follow the GitHub Actions runner guide for CI artifact builds.
cannot execute binary file: Exec format error often means an architecture mismatch: amd64 versus arm64. Verify uname -m and rebuild for the target.
No such file or directory may indicate a missing dynamic loader or script interpreter, not a missing executable. Inspect:
file ./myapp # 看是 statically linked 还是 dynamically linked
ldd ./myapp # 动态链接的话,看依赖什么
Rebuild with CGO_ENABLED=0 only if dependencies support pure Go; otherwise supply a compatible loader/library environment.
For permission denied, check executable ownership/mode and chmod +x myapp, mount noexec policy, directory permissions and writes blocked by ProtectSystem=strict. Inspect journalctl -u myapp for the specific failing operation.
Check WorkingDirectory, absolute paths and deployed assets. go:embed simplifies resource coupling when suitable.
Configure GOMEMLIMIT and profile the live allocations/goroutines. Unclosed response bodies lacking Close() and time.Ticker without Stop() can retain resources; inspect actual ownership/lifetimes. Swap/ZRAM can buffer pressure but does not repair leaks.
An eight-hour offset in the source reflects an Asia/Shanghai-versus-UTC example, not every reader's expected zone. Choose the application's actual IANA zone/UTC and make timezone data available. You can embed it with -tags timetzdata:
go build -tags timetzdata -o dist/myapp ./cmd/myapp
Carry the other target/static build flags when needed; the timezone-only example does not replace them.
Check systemctl status myapp, and whether localhost resolves differently from 127.0.0.1 for the chosen upstream. See 502/504 diagnosis.
Use sudo ss -lntp 'sport = :3000' to identify the owner, without killing unrelated services. See port conflicts and the logging guide.
FROM scratch can produce a small pure-Go image, but the source's under-20-MB figure is workload-dependent. Include CA certificates, timezone data and any necessary runtime files. A single systemd service may be simpler; Compose helps coordinate several services.
| Choice | systemd | Docker |
|---|---|---|
| Artifact | Binary and required files | Image |
| Isolation | Configured service sandbox | Configured container isolation; privileged mounts can weaken it |
| Size | Application-dependent | A scratch example may be under 20 MB |
| Multiple services | Separate units/configuration | Compose orchestration |
| Diagnosis | Host service path | Additional container/network layer |
Choose according to operational needs, not a universal isolation ranking. See Compose resource limits. CPU requirements depend on workload: Go's GC/scheduler can use multiple cores, and low memory needs are not guaranteed. RackNerd annual offerings and Vultr hourly flexibility are options to verify; DMIT mainland-China CN2 GIA routes serve that particular connectivity requirement. Use the sizing guide.
- Node.js deployment for a companion service;
- Python deployment for Django/FastAPI;
- VPS sizing for measured resource selection;
- Docker deployment for a container approach;
- Backup/restore drills for databases, uploads and secrets: reverting a binary does not restore data or undo migrations.