How to Use Docker Compose with a Go Application

Use docker-compose.yml to define your Go app service and run docker-compose up --build to compile and launch it.

Use Docker Compose to define your Go application and its dependencies in a docker-compose.yml file, then run docker-compose up --build to compile and start the services.

version: '3.8'
services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - GOOS=linux
      - GOARCH=amd64
  1. Create a Dockerfile in your project root with FROM golang:1.21-alpine, WORKDIR /app, COPY . ., RUN go build -o main ., and CMD ["./main"].
  2. Add the docker-compose.yml file shown above to define the service.
  3. Run docker-compose up --build to build the image and start the container.