Docker with Go
Let's dockerize your Go app! You can read my previous article about Docker and this article if you don't know about Docker.
First, we need to write the
Dockerfile. Based on the official Docker image of Go, https://hub.docker.com/_/golang, this simple script is enough to Dockerize our Go apps.
1 2 3 4 5 6 7 8 9 FROM golang:1.17 WORKDIR /go/src/app COPY . . RUN go get -d -v ./... RUN go install -v ./... CMD ["app"]
Second, let's build the Docker image with the command
docker build -t my-golang-app .. The parameter of
-t is to name the Docker image. We will get the Docker image with a size of about 1.26GB.
The one we previously made was big, right? It will cost a lot of storage if we deploy it. Here is a tip to save more storage. We build or compile the Go app then bring it to the Alpine image. It will give us an extremely light size for the Docker image. Here is the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 FROM golang AS BUILDER LABEL stage="builder" WORKDIR /app ARG CGO_ENABLED=0 COPY . . RUN go build -o app FROM alpine LABEL maintainer="Aristo Rinjuang <firstname.lastname@example.org>" WORKDIR /app COPY --from=BUILDER /app/app . COPY --from=BUILDER /app/.env.example .env EXPOSE 8080 CMD ["./app"]
The Dockerfile above I made as a basic. It will save a lot of Docker image size. Feel free to customize it as you need. Here is the explanation of the script.
- We label the first build as a "builder" because that will be a temporary image. We will delete it.
ARG CGO_ENABLED=0. It disables the cgo tool and makes the build size smaller. Refer to https://pkg.go.dev/cmd/cgo.
- We label the build with a name and an email as a maintainer at the second build. The size is very light. It is good to deploy or for the production.
- We copy the binary from the builder and other necessary files like
- Last, of course, we need to expose the port that the app use.
The Docker image of my Go app I made with the
Dockerfile above is about 18.4MB. There is a huge difference if we compare it with the previous
Dockerfile that has 1.26GB.
On macOS, Docker images from the builder are automatically deleted. I have no idea about Windows. They do exist on Linux and we need to delete them manually with this command,
docker image prune --filter "label=stage=builder".