I am writing a Dockerfile
to build an application. I know that you can copy files out of the container manually with
docker cp <containerId>:/file/path/within/container /host/path/target
(see Copying files from Docker container to host), but I would like to just run
docker build
and have it dump the build artifacts created by my Dockerfile
somewhere on my host file system.
Is there a command I can use within the Dockerfile to copy out of the container and into the host? Like the opposite of COPY
?
To summarize, follow these steps to copy a file from a Docker container to a host machine: Obtain the name or id of the Docker container. Issue the docker cp command and reference the container name or id. The first parameter of the docker copy command is the path to the file inside the container.
Docker cp Command It can only be used to copy files between the host system and a single container.
As per Docker docs, API version 1.40 added
Custom build outputs
Which is intended for what you want:
By default, a local container image is created from the build result. The --output (or -o) flag allows you to override this behavior, and a specify a custom exporter. For example, custom exporters allow you to export the build artifacts as files on the local filesystem instead of a Docker image, which can be useful for generating local binaries, code generation etc.
For example
$ docker build --output type=tar,dest=out.tar .
with multi-stage Dockerfile
FROM golang AS build-stage RUN go get -u github.com/LK4D4/vndr FROM scratch AS export-stage COPY --from=build-stage /go/bin/vndr /
The --output option exports all files from the target stage. A common pattern for exporting only specific files is to do multi-stage builds and to copy the desired files to a new scratch stage with COPY --from.
Adding to @Marakai excellent answer, one has to set the env variable DOCKER_BUILDKIT=1. So the command would be:
$ DOCKER_BUILDKIT=1 docker build --output type=tar,dest=out.tar .
Or one could split into two commands:
$ export DOCKER_BUILDKIT=1 $ docker build --output type=tar,dest=out.tar . # to gen into a tar file
Or to save the files without forming a tar file:
$ mkdir out $ docker build --output out .
The files will be copied to the directory out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With