How To Build a Tiny Go Server Docker Image

Greg James
4 min readApr 27, 2024

In the rapidly evolving world of software development, the efficiency and security of application deployment have become paramount. As developers seek to streamline their development processes and ensure that their applications are as lightweight and secure as possible, technologies like Docker and best practices such as multi-stage builds have become essential tools. This article delves into a practical example of using Docker to build a Go application. We will break down a Dockerfile designed to create a secure and minimal container by utilizing Alpine Linux, a popular choice for its minimal footprint, and explore how multi-stage builds can optimize both the build process and the security of the final container.

Code:

FROM golang:alpine as golang

# Create appuser
ENV USER=appuser
ENV UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
"${USER}"

WORKDIR /app
COPY /models ./models/
COPY go.mod go.sum ./
RUN go mod download && go mod verify
RUN apk add --no-cache upx

COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -gcflags=all="-l" -o /server .

RUN upx -9 -v --ultra-brute --lzma --best /server

FROM scratch

COPY --from=golang /etc/ssl/certs/ca-certificates.crt…

--

--

Greg James

Let's get better together! Follow for tips and insights to help you grow in both your skills and confidence as a developer!