All posts

Fix MemoryError in Go When Deploying

Resolve out-of-memory errors during Go application builds in CI/CD pipelines, covering cgo compilation and Docker build contexts.

Go Build Memory Errors During Deployment

Go builds are usually fast and light, but certain conditions cause the compiler or linker to consume excessive memory during CI/CD deployment.

Large CGo Projects

Projects with CGo dependencies (like SQLite, OpenCV) invoke the C compiler, which can be memory-hungry:

# Use CGO_ENABLED=0 if you don't need C libraries
ENV CGO_ENABLED=0
RUN go build -o /app/server ./cmd/server

If CGo is required, increase the build container's memory:

# GitHub Actions
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: go build -o server ./cmd/server
        env:
          GOGC: 50  # More frequent GC during build

Docker Build Context Too Large

Sending a huge build context exhausts Docker daemon memory:

# .dockerignore
.git
node_modules
tmp/
*.test
vendor/  # If using go mod download in Dockerfile

Multi-Stage Builds

FROM golang:1.22-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -ldflags="-s -w" -o /app/server

FROM alpine:3.19
COPY --from=builder /app/server /app/server
CMD ["/app/server"]

The -ldflags="-s -w" strips debug info, reducing the binary and linker memory.

GOGC Tuning

During builds, a lower GOGC value trades CPU for memory:

GOGC=50 go build ./...

Bugsly tracks deployment events via CI webhook, correlating build failures with changes that introduced heavy dependencies.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free