Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 19, 2021 04:46 am GMT

Dockerfile for Go

Each time I start a new Go project, I repeat many steps.
Like set up .gitignore, CI configs, Dockerfile, ...

So I decide to have a baseline Dockerfile like this:

FROM golang:1.18beta1-bullseye as builderWORKDIR /buildCOPY go.mod .COPY go.sum .COPY vendor .COPY . .RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOAMD64=v3 go build -o ./app main.goFROM gcr.io/distroless/base-debian11COPY --from=builder /build/app /appENTRYPOINT ["/app"]

I use multi-stage build to keep my image size small.
First stage is Go official image,
second stage is Distroless.

Before Distroless, I use Alpine official image,
There is a whole discussion on the Internet to choose which is the best base image for Go.
After reading some blogs, I discover Distroless as a small and secure base image.
So I stick with it for a while.

Also, remember to match Distroless Debian version with Go official image Debian version.

FROM golang:1.18beta1-bullseye as builder

This is Go image I use as a build stage.

WORKDIR /buildCOPY go.mod .COPY go.sum .COPY vendor .COPY . .

I use /build to emphasize that I am building something in that directory.

The 4 COPY lines are familiar if you use Go enough.
First is go.mod and go.sum because it defines Go modules.
The second is vendor because I use it a lot, this is not necessary but I use it because I don't want each time I build Dockerfile, I need to redownload Go modules.

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOAMD64=v3 go build -o ./app main.go

This is where I build Go program.
CGO_ENABLED=0 because I don't want to mess with C libraries.
GOOS=linux GOARCH=amd64 is easy to explain, Linux with x86-64.
GOAMD64=v3 is new since Go 1.18,
I use v3 because I read about AMD64 version in Arch Linux rfcs. TLDR's newer computers are already x86-64-v3.

FROM gcr.io/distroless/base-debian11COPY --from=builder /build/app /appENTRYPOINT ["/app"]

Finally, I copy app to Distroless base image.


Original Link: https://dev.to/youngyoshie/dockerfile-for-go-4jjp

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To