Home >Backend Development >Golang >How to Build Static Binaries in Go for Docker Images from Scratch?

How to Build Static Binaries in Go for Docker Images from Scratch?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 17:17:30844browse

How to Build Static Binaries in Go for Docker Images from Scratch?

Flags for Creating Static Binaries in Go

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:

  • CGO_ENABLED=0: Disables CGO (Call Go from C), which is a feature that allows Go programs to call C code. This is necessary because Linux dynamically links C libraries, which can cause issues when building static binaries.
  • -a: Forces rebuilding of all packages and dependencies, regardless of whether they are up-to-date.
  • -ldflags '-extldflags "-static"': Specifies flags to pass to the external linker. In this case, -static indicates that static linking should be used, ensuring that all required libraries are embedded into the binary.

It is important to use both CGO_ENABLED=0 and -ldflags '-extldflags "-static"' because:

  • CGO_ENABLED=0 disables CGO but does not guarantee static linking.
  • -ldflags '-extldflags "-static"' forces static linking but does not disable CGO.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn