All Guides
Frameworks10 min read

Deploy Go Applications

Build and deploy Go applications with multi-stage Docker builds, static binary optimization, and health checks.

1.Go Module Configuration

Ensure your Go project uses modules and has proper build configuration.

  1. Initialize module: go mod init github.com/user/project
  2. Ensure go.mod and go.sum are committed
  3. Use go mod tidy to clean dependencies
  4. Vendor directory optional: go mod vendor for offline builds

2.Dockerfile Best Practices

Use multi-stage builds for small, secure production images.

  1. Stage 1: Build — use golang:alpine with build tools
  2. Stage 2: Runtime — use alpine or scratch for minimal image
  3. Copy binary from build stage: COPY --from=builder /app/main /app/main
  4. Run as non-root user for security
  5. Expose port via ENV PORT=8080 and EXPOSE 8080
# Multi-stage Dockerfile for Go
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /app/main .

FROM alpine:3.19
RUN apk --no-cache add ca-certificates
WORKDIR /app
COPY --from=builder /app/main .
RUN adduser -D -g '' appuser
USER appuser
ENV PORT=8080
EXPOSE 8080
ENTRYPOINT ["/app/main"]

3.Build Optimization

Optimize binary size and build speed.

  1. Use CGO_ENABLED=0 for static linking
  2. Strip debug symbols: -ldflags='-s -w'
  3. Use go build -trimpath for reproducible builds
  4. Leverage Docker layer caching: copy go.mod/go.sum first

4.Health Check Endpoints

Add health checks for container orchestration.

  1. Implement /health or /healthz endpoint
  2. Return 200 OK with {status: "ok"}
  3. Include dependency checks (DB, Redis, external APIs)
  4. Oxaploy uses this for container health checks
// healthz.go
package main
import (
  "encoding/json"
  "net/http"
)

func healthHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}

func main() {
  http.HandleFunc("/healthz", healthHandler)
  // ... rest of your app
}