How to Create a Dockerfile for Go Applications
To create a
Dockerfile for a Go application, use a multi-stage build starting with a Go image to compile your code, then copy the compiled binary into a small base image like scratch or alpine. This approach keeps the final image small and efficient.Syntax
A typical Go Dockerfile uses multi-stage builds with these parts:
- FROM: Specifies the base image, usually
golangfor building. - WORKDIR: Sets the working directory inside the container.
- COPY: Copies source code into the container.
- RUN: Runs commands like
go buildto compile the app. - FROM (second stage): Uses a minimal image like
scratchoralpinefor the final container. - COPY: Copies the compiled binary from the build stage.
- CMD: Defines the command to run the app.
dockerfile
FROM golang:1.20 AS builder WORKDIR /app COPY . . RUN go build -o myapp FROM scratch COPY --from=builder /app/myapp /myapp CMD ["/myapp"]
Example
This example shows a complete Dockerfile for a simple Go app that prints "Hello, Docker!". It builds the app in the first stage and creates a tiny final image with only the binary.
dockerfile
FROM golang:1.20 AS builder WORKDIR /app COPY . . RUN go build -o hello FROM scratch COPY --from=builder /app/hello /hello CMD ["/hello"]
Output
Hello, Docker!
Common Pitfalls
Common mistakes when creating a Go Dockerfile include:
- Not using multi-stage builds, which leads to large images with unnecessary build tools.
- Forgetting to copy all source files before building, causing build errors.
- Using
scratchwithout static linking, which causes runtime errors. - Not setting the correct
CMDto run the binary.
Always ensure your Go binary is statically linked (default for Go) when using scratch as the base.
dockerfile
### Wrong: single stage, large image FROM golang:1.20 WORKDIR /app COPY . . RUN go build -o myapp CMD ["./myapp"] ### Right: multi-stage, small image FROM golang:1.20 AS builder WORKDIR /app COPY . . RUN go build -o myapp FROM scratch COPY --from=builder /app/myapp /myapp CMD ["/myapp"]
Quick Reference
Tips for creating Go Dockerfiles:
- Use
golangimage for building. - Use multi-stage builds to keep images small.
- Copy only the compiled binary to the final image.
- Use
scratchoralpineas the final base image. - Set
CMDto run your binary.
Key Takeaways
Use multi-stage builds to separate build and runtime environments for smaller images.
Start with the official golang image to compile your Go code inside the container.
Copy only the compiled binary to a minimal base image like scratch for efficiency.
Ensure your Go binary is statically linked when using scratch as the base image.
Set the CMD instruction to run your compiled Go binary in the container.