by aodin · 8y ago · 0 comments
The default Go Docker images include everything needed to compile Go. But once you have a binary, you really only need an image capable of running your binary. I've seen images sizes reduced by over 95%.
Revising the example in the article:
FROM golang:1.10
COPY . /go/src/bitbucket.code.company-name.com.au/scm/code
WORKDIR /go/src/bitbucket.code.company-name.com.au/scm/code/
RUN CGO_ENABLED=0 go build main.go
FROM alpine:3.7
RUN apk add --no-cache ca-certificates
COPY --from=0 /go/src/bitbucket.code.company-name.com.au/scm/code/main .
CMD ["./main"]
The `CGO_ENABLED=0` and `apk` are oddities of Alpine Linux specifically. The image you choose to run your binary may not need these. FROM golang:1.10
WORKDIR /go/src/bitbucket.code.company-name.com.au/scm/code
COPY ./ ./
RUN CGO_ENABLED=0 go build -a -installsuffix cgo -o /dist/main .
FROM scratch
COPY --from=0 /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=0 /go/src/bitbucket.code.company-name.com.au/scm/code/dist/main /
ENTRYPOINT ["/main"]
It requires a bit more "magic", but is a smaller build at the end.Those tools aren't optimized for running arbitrary binaries - hence containers.
It feels so good to skip over all the Docker tools, config and services to build a Go app.
I wrote up more details here:
https://github.com/nzoschke/gofaas/blob/master/docs/dev-pack...
I wrote up some documentation about this for my use case just in case I ever have to go back and change it.
You can see it here: https://fn.lc/post/docker-scratch/
Please don't run untrusted code in Docker, it's not designed for security.
https://security.stackexchange.com/questions/107850/docker-a...
Also, port and volume mapping, so the container/go binary does not need to know physical/host pathnames to data files.
edit
I misunderstood the parent, they meant to use `golang:1.10-alpine` as the build image, not the run image, as in:
FROM golang:1.10-alpine
COPY . /go/src/bitbucket.code.company-name.com.au/scm/code
WORKDIR /go/src/bitbucket.code.company-name.com.au/scm/code/
RUN go build main.go
FROM alpine:3.7
RUN apk add --no-cache ca-certificates
COPY --from=0 /go/src/bitbucket.code.company-name.com.au/scm/code/main .
CMD ["./main"]
Which works! Thank you!