How to Dockerize a Go API with a Database

Dockerize a Go API with a database using a multi-stage Dockerfile and docker-compose to manage the API and PostgreSQL services.

Create a Dockerfile to build the Go binary and a docker-compose.yml to orchestrate the API and database containers.

FROM golang:1.23-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o main .

FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/main .
EXPOSE 8080
CMD ["./main"]
version: '3.8'
services:
  api:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - db
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/mydb
  db:
    image: postgres:16
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=mydb

Run docker-compose up --build to start both services.