Copy folder from container to host after docker run

334 views Asked by At

I have an image that will create a catalog after running the container. What I want to do is to run the container with mounted volume and after running it I want to copy this catalog to the mounted host folder.

Tried several ways but couldn't get it done. Most of the documentation talks about docker cp or docker volumes.

What I want to do is to run:

docker run -t -d -v test/:/test

and then when I would create any file in test dir in the container it will appear in the test folder on the host.

CP works fine but it's manual. I want to just run the container and it will copy necessary files from inside to mounted directory.

1

There are 1 answers

0
David Maze On

The docker run -v option is the right way. Note, however, that the host-side path needs to be an absolute path, so the most common (Linux/Unix Bourne shell) syntax is

docker run -v "$PWD/test:/test" ...

If you're using Docker Compose, its volumes: option does accept relative paths, which are considered relative to the location of the docker-compose.yml file.

The important caveats with this approach is that the container directory /test must not be the directory that contains the application code, and that the permissions and numeric ownership of the host directory propagate into the mounted volume. It's also common to run the container with the numeric user ID that the current host user has; there is no requirement to "create the user" in the container, and something of an anti-pattern to build a specific user ID in the image.

A complete extended command might look like:

docker run \
  -d \                    # in the background
  -u $(id -u):$(id -g) \  # with the host user and group IDs
  -v "$PWD/test:/test" \  # with a bind mount
  the-image \
  /app/run_tests -o /test/catalog.json  # overriding the command
                                        # with specific container paths