Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker copy file to host from within dockerfile

Tags:

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?

like image 829
JamesFaix Avatar asked Apr 03 '18 20:04

JamesFaix


People also ask

How do I copy a file from Docker container to host from inside the container?

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.

Which Dockerfile command defines files to copy from the host file system onto the container?

Docker cp Command It can only be used to copy files between the host system and a single container.


2 Answers

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.

like image 79
Marakai Avatar answered Sep 20 '22 17:09

Marakai


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.

like image 27
HAltos Avatar answered Sep 21 '22 17:09

HAltos