Docker Setup for Go Development

This is a short and sweet article on running a Go application using Docker. This is a generic example and many use-cases will differ and so have totally different setups. In our examples we’re also using Docker and docker-compose both of which you will need already installed and setup on your machine for this to work.

To begin, we’ll create our two files, the Dockerfile and docker-compose.yaml

Dockerfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#get a base image
FROM golang:alpine

# Set necessary environmet variables needed for our image
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

# Move to working directory /build
WORKDIR /build

# Copy and download dependency using go mod
COPY go.mod .
COPY go.sum .
RUN go mod download

# Copy the code into the container
COPY . .

RUN go build -v -o goapp
CMD ["/build/goapp"]

We use alpine in this example as it’s a lightweight OS which lends itself nicely to container images. We then set some fo the environment variables necessary to build to program (like cgo) and download the dependencies with go mod.

docker-compose.yaml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
version: "3.9"
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: 'web'
    ports:
      - "8080:8080"
    env_file:
      - .env

We tell docker-compose to look at our Dockerfile and give it a name of ‘web’ (you can be more inventive if you like!) and map it to port 8080.

.env (optional)

1
EXAMPLE_ENV=secret

Because we referenced ’env_file’ in our docker-compose.yaml we can also read environment variables directly from this file, which is very useful for local development.

Running it…

Once we have all our files setup, we can run docker compose to kick everything off.

1
docker-compose up --build

docker clear out with system prune