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.
- Initialize module: go mod init github.com/user/project
- Ensure go.mod and go.sum are committed
- Use go mod tidy to clean dependencies
- Vendor directory optional: go mod vendor for offline builds
2.Dockerfile Best Practices
Use multi-stage builds for small, secure production images.
- Stage 1: Build — use golang:alpine with build tools
- Stage 2: Runtime — use alpine or scratch for minimal image
- Copy binary from build stage: COPY --from=builder /app/main /app/main
- Run as non-root user for security
- 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.
- Use CGO_ENABLED=0 for static linking
- Strip debug symbols: -ldflags='-s -w'
- Use go build -trimpath for reproducible builds
- Leverage Docker layer caching: copy go.mod/go.sum first
4.Health Check Endpoints
Add health checks for container orchestration.
- Implement /health or /healthz endpoint
- Return 200 OK with {status: "ok"}
- Include dependency checks (DB, Redis, external APIs)
- 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
}