CodeX
Published in

CodeX

Set up a Multi-Stage Docker Build for Go Applications

A good start is half the job done

Photo by Pankaj Patel on Unsplash

Requirements

Let’s write some code

package main

import "fmt"

func main() {
fmt.Println("Hello World!")
}

Golang base image

FROM golang:1.16-alpine

# Create a workspace for the app
WORKDIR /app

# Download necessary Go modules
COPY src/go.mod .
RUN go mod download

# Copy over the source files
COPY src/*.go ./

# Build
RUN go build -o /main

ENTRYPOINT ["/main"]
REPOSITORY               TAG       IMAGE ID       CREATED              SIZE
hello-world-golang1.16 latest 68b776701cbe About a minute ago 304MB
#
# Builder
#

FROM golang:1.16-alpine AS builder

# Create a workspace for the app
WORKDIR /app

# Download necessary Go modules
COPY src/go.mod .
RUN go mod download

# Copy over the source files
COPY src/*.go ./

# Build
RUN go build -o /main

#
# Runner
#

FROM gcr.io/distroless/base-debian10 AS runner

WORKDIR /

# Copy from builder the final binary
COPY --from=builder /main /main

USER nonroot:nonroot

ENTRYPOINT ["/main"]
REPOSITORY               TAG       IMAGE ID       CREATED              SIZE
hello-world-debian latest 7ad8a5965a06 About a minute ago 21.1MB
hello-world-golang1.16 latest 68b776701cbe About a minute ago 304MB
#
# Runner
#

# FROM gcr.io/distroless/base-debian10 AS runner
FROM scratch AS runner
REPOSITORY               TAG       IMAGE ID       CREATED              SIZE
hello-world-scratch latest eb41c9777973 58 seconds ago 1.94MB
hello-world-debian latest 7ad8a5965a06 About a minute ago 21.1MB
hello-world-golang1.16 latest 68b776701cbe About a minute ago 304MB

Wrapping it up

--

--

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Koen Verburg

Software Engineer based in Rotterdam — Photographer, Art Enthusiast, Dreamer, and thinker.