Additional flags to allow execution of binary on scratch - based images

I am building a simple go app and wanted to minimise the size of my docker image.

I followed the initial steps of a very popular article on medium.

Do my initial Dockerfile became

FROM golang:alpine AS builder
RUN apk update && apk add --no-cache git
WORKDIR $GOPATH/src/github.com/myrepo/mybot/
COPY . .
RUN go get -d -v
# Build the binary.
RUN go build -o /go/bin/mybot

FROM scratch
COPY --from=builder /go/bin/mybot /go/bin/mybot
ENTRYPOINT ["/go/bin/mybot"]

However, when I tried to execute my image I got the following error:

standard_init_linux.go:211: exec user process caused "no such file or directory"

The problem was solved when I replaced the go build command with the following:

RUN CGO_ENABLED=0 go build -o /go/bin/workabot -a -ldflags '-extldflags "-static"' . 

Why setting CGO_ENABLED=0 and setting the flags -a and -ldflags '-extldflags "-static" allow the program to run on the scratch image?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.