Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy files from a docker image - dockerfile cmd

During build time, I want to copy a file from the image (from folder /opt/myApp/myFile.xml), to my host folder /opt/temp In the Dockerfile, I'm using the --mount as follows, trying to mount to my local test folder:

RUN --mount=target=/opt/temp,type=bind,source=test cp /opt/myApp/myFile.xml /opt/temp

I'm building the image successfully, but the local test folder is empty any ideas?

like image 421
Mary1 Avatar asked Aug 04 '20 08:08

Mary1


People also ask

Can I copy files from docker image?

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.

What is CMD instruction in Dockerfile?

The CMD command​ specifies the instruction that is to be executed when a Docker container starts.

Can use Dockerfile with out CMD?

You can clearly build a docker image from Dockerfile without CMD or ENTRYPOINT as shown by OP.


1 Answers

Copying files from the image to the host at build-time is not supported.
This can easily be achieved during run-time using volumes.

However, if you really want to work-around this by all means, you can have a look in the custom build outputs documentation, that introduced support for this kind of activity.

Here is a simple example inspired from the official documentation:

Dockerfile

FROM alpine AS stage-a
RUN mkdir -p /opt/temp/
RUN touch /opt/temp/file-created-at-build-time
RUN echo "Content added at build-time" > /opt/temp/file-created-at-build-time

FROM scratch as custom-exporter
COPY --from=stage-a /opt/temp/file-created-at-build-time .

For this to work, you need to launch the build command using these arguments:

DOCKER_BUILDKIT=1 docker build --output out .

This will create on your host, aside the Dockerfile, a directory out with the file you need:

.
├── Dockerfile
└── out
    └── file-created-at-build-time
cat out/file-created-at-build-time 
Content added at build-time

like image 70
Neo Anderson Avatar answered Oct 12 '22 16:10

Neo Anderson