Docker multi-stage builds
30 September 2025 (Updated 30 September 2025)
Example of a multi-stage Dockerfile
You can use multi-stage builds in a single Dockerfile like so:
# ==============================================================================
# Stage: build
# ==============================================================================
# Use the golang image as a base
FROM golang:1.25 AS build
# Set working directory to src/
WORKDIR /src
# Copy a simple Go program to main.go
COPY <<EOF ./main.go
package main
import "fmt"
func main() {
fmt.Println("hello, world")
}
EOF
# Compile main.go into a binary at /bin/hello
RUN go build -o /bin/hello ./main.go
# ==============================================================================
# Stage: main
# ==============================================================================
FROM scratch
COPY --from=build /bin/hello /bin/hello
CMD ["/bin/hello"]
We have two stages in the above Dockerfile:
buildmain
The build stage creates a /bin/hello binary.
The main stage copies the /bin/hello binary from the build stage to bin/hello and then executes it.
Stop at a specific build stage
You can also build an image upto a specific stage:
docker build --target build -t hello .
Running the command above will create an image with all artifacts from the build stage only. This can be useful for:
- Debugging a specific build stage
- If you want a
basestage and adevelopmentstage where the latter adds additional development tools like XDebug for PHP..
Copy artifacts from an external image
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf
Links
Tagged:
Docker