Copy files from Container to host using Dockerfile

It is probably a bad idea to copy files from the container to the host during build. You should seriously consider your use case.

However, it can be done and I will share with you a procedure because it is an opportunity for me to show off my Docker knowledge - not because I think you should do this. There are other ways to do this. My way is not better or worse - they are all kludges.

  1. Modify your dockerd configuration as explained in https://success.docker.com/article/how-do-i-enable-the-remote-api-for-dockerd. Basically add -H tcp://0.0.0.0:2376. This is a very risky procedure b/c it opens you open to be rooted by anyone on your network. There are ways to mitigate this risk with authentication, but really the best way is to JUST DON'T DO IT.
  2. Modify your Dockerfile:
    1. Add a ARG DOCKER_HOST before the RUN blocks.
    2. In the run blocks:
      1. Install docker.
      2. Add `export DOCKER_HOST=${DOCKER_HOST}.
      3. Add docker container run --mount type=bind,source=/,destination=/srv/host alpine:3.4 ...
  3. Determine the IP address of your host computer. Let us assume it is 10.10.20.100.
  4. Modify your build command by adding --build-arg DOCKER_HOST=10.10.20.100.

In step 2.2.3 you have rooted the host computer and you can do whatever you want - including writing to any file.

This is a dumb idea, but it shows that since you can run docker from within a build, there really is not anything you can not do from inside a build. If you want to run a gui app from inside a build you can do it.


There is no specific way to do this during the build process. At runtime you can copy files out via a mounted volume, but this is not available during the build process. If you just mean at run time then you can do things like docker run -v .:/out myimage -- cp -r /from/somewhere /out or similar.