Skillversitas

Docker Go

How to run a Go application in Docker.

Go Dockerfile

# Stage 1: Build
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o server

# Stage 2: Production
FROM scratch
COPY --from=builder /app/server /server
EXPOSE 8080
CMD ["/server"]

docker-compose.yml

version: '3.8'

services:
  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      - DB_HOST=database
      - DB_PORT=5432
      - DB_NAME=myapp
    networks:
      - app-net

  database:
    image: postgres:15
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - app-net

networks:
  app-net:

volumes:
  postgres-data:

Use Case: Go Application

# Run Go
docker-compose up -d

# Build
docker-compose build

# Test
docker-compose exec api go test ./...

Everyday Use Case

Case: A developer needs to run Go.

# Build
docker-compose build

# Run
docker-compose up -d

# Go commands
docker-compose exec api go test ./...
docker-compose exec api go build -o server

Best Practices

  1. Multi-stage build: For a smaller image
  2. Scratch image: For production
  3. Non-root user: For security
  4. Health check: For monitoring

Conclusion

Go in Docker is easy to set up. Use a multi-stage build to produce a very small image.