When building docker images from scratch, static binaries are necessary to prevent errors during execution. However, the command RUN go build -o /go/bin/myapp may produce binaries that fail with "no such file or directory" errors.
To overcome this, the following flags are required:
RUN CGO_ENABLED=0 go build -o /go/bin/myapp -a -ldflags '-extldflags "-static"' .
Explanation:
It is important to use both CGO_ENABLED=0 and -ldflags '-extldflags "-static"' because:
By using both flags, you can ensure that the resulting binary is static and does not rely on any external libraries.
The above is the detailed content of How to Build Static Binaries in Go for Docker Images from Scratch?. For more information, please follow other related articles on the PHP Chinese website!