Reduce size of docker image for Golang

The Feature!

Docker 17.05 came up with a concept called multi-stage builds

The Problem

Default image builds can have size easily more than 800MB.

The Approach

  • Stage 1. Compile the app in default image
  • Stage 2. Copy compiled app in alpine

Dockerfile

FROM golang:1.10.1 as builder
WORKDIR /go/src/api_redis
#Get Requirements
RUN go get -d -v github.com/go-redis/redis
#Get Requirements
RUN go get -d -v github.com/OneOfOne/xxhash
COPY main.go  .
#Compile codes
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o api_redis .

#Get compiled app
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/api_redis/api_redis .
CMD ["./api_redis"]
sudo docker build -t api_redis:v1 .

This kind of build has reduced the images size to only 10.3MB


sudo docker images

REPOSITORY                                      TAG                 IMAGE ID            CREATED             SIZE
api_redis                                       v1                  3b3f571be4da        4 seconds ago       10.3MB
golang                                          latest              6b369f7eed80        3 days ago          794MB

Reduce size of docker image for Golang

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top