In this article, we will walk through the creation of an optimized Dockerfile for building and running a Go application. This Dockerfile will focus on building only the binary of the Go application, resulting in a smaller and more efficient Docker image.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
## Dockerfile for Building a Go Application
```Dockerfile
# Stage 1: Build the Go Binary
FROM golang:1.17 as builder
# Set the working directory inside the container
WORKDIR /app
# Copy the Go application source code into the container
COPY . .
# Set environment variables
ENV CGO_ENABLED=0
# Fetch dependencies and build the Go binary
RUN go get -d -v ./...
RUN go build -o /tmp/api-server .
# Stage 2: Create a minimal runtime image
FROM scratch
# Copy the binary from the builder stage into the minimal image
COPY --from=builder /tmp/api-server /usr/bin/api-server
# Define the command to run when the container starts
CMD ["api-server", "start"]
|
In this Dockerfile, we use a multi-stage build to optimize the final Docker image. Here’s a breakdown of what each section does: