Last active
December 3, 2023 12:27
-
-
Save dmiro/9f4a03433e0646e47a207408641d5cd1 to your computer and use it in GitHub Desktop.
Docker Multi State Build
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## https://docs.docker.com/build/building/multi-stage/ | |
## With multi-stage builds, you use multiple FROM statements in your Dockerfile. | |
## Each FROM instruction can use a different base, and each of them begins a new stage of the build. | |
## You can selectively copy artifacts from one stage to another, leaving behind everything you don't | |
## want in the final image. | |
# syntax=docker/dockerfile:1 | |
FROM golang:1.21 as build | |
WORKDIR /src | |
COPY <<EOF /src/main.go | |
package main | |
import "fmt" | |
func main() { | |
fmt.Println("hello, world") | |
} | |
EOF | |
RUN go build -o /bin/hello ./main.go | |
FROM scratch | |
COPY --from=build /bin/hello /bin/hello | |
CMD ["/bin/hello"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Stop at a specific build stage https://docs.docker.com/build/building/multi-stage/#stop-at-a-specific-build-stage
When you build your image, you don't necessarily need to build the entire Dockerfile including every stage. You can specify a target build stage. The following command assumes you are using the previous Dockerfile but stops at the stage named build:
docker build --target build -t hello .
Use an external image as a stage https://docs.docker.com/build/building/multi-stage/#use-an-external-image-as-a-stage
When using multi-stage builds, you aren't limited to copying from stages you created earlier in your Dockerfile. You can use the COPY --from instruction to copy from a separate image, either using the local image name, a tag available locally or on a Docker registry, or a tag ID. The Docker client pulls the image if necessary and copies the artifact from there. The syntax is:
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf