Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export directory created inside the Docker image to the host machine?

The program I'm running inside the Docker image, first creates a directory and writes some file into the directory.

To transfer the directory onto the host machine, I've mounted a datadir/ and then moved the directory created inside the image into the mounted directory, e.g.:

mkdir datadir
DATADIR=datadir/

docker run -i \
-v $(pwd)/$DATADIR:/$DATADIR/ ubuntu \
bash -c "mkdir /x1 && echo 'abc' > x1/test.txt && mv x1 $DATADIR"

But when I tried to access datadir/x1, it has root as the owner and it comes with read-only permissions:

$ mv datadir/x1/ .
mv: cannot move 'datadir/x1/' to './x1': Permission denied

$ ls -lah datadir/x1/
total 12K
drwxr-xr-x 2 root root   4.0K Jun 28 16:38 .
drwxrwxr-x 3 alvas alvas 4.0K Jun 28 16:38 ..
-rw-r--r-- 1 root root      4 Jun 28 16:38 test.txt

Is mounting the additional volume and copying the created directory inside the image the right approach to move files between the Docker image and the host machine? If not, what's the "canonical" way to perform the same operation?

About the directory permissions, what should be the correct way to assign the host machine permission to any files inside the mounted volume?


I've tried to chmod -R 777 inside the Docker image but I don't think that's the safe approach, i.e.:

$ docker run -i -v $(pwd)/$DATADIR:/$DATADIR/ -i ubuntu bash -c "mkdir /x1 && echo 'abc' > x1/test.txt && mv x1 $DATADIR && chmod -R 777 $DATADIR"

$ mv datadir/x1/ .

$ ls -lah x1
total 12K
drwxrwxrwx  2 root root   4.0K Jun 28 16:47 .
drwxrwxr-x 12 alvas alvas 4.0K Jun 28 16:47 ..
-rwxrwxrwx  1 root root      4 Jun 28 16:47 test.txt
like image 941
alvas Avatar asked Nov 03 '25 03:11

alvas


1 Answers

To avoid permission issues use docker cp

For example:

# This is the directory you want to save the outputs
mkdir datadir

# We create a directory and file inside it, inside the Docker image.
# And we are naming the Docker image "thisinstance"
docker run -i --name thisinstance ubuntu \
bash -c "mkdir /x1 && echo 'abc' > x1/test.txt"

# Copies the new directory inside the Docker image to the host.
docker cp thisinstance:/x1 datadir/

# Destroy the temporary container
docker rm thisinstance

# Check the ownership of the directory and file
ls -lah datadir/x1/

[out]:

drwxr-xr-x  3 alvas  679754705   102B Jun 29 10:36 ./
drwxr-xr-x  3 alvas  679754705   102B Jun 29 10:36 ../
-rw-r--r--  1 alvas  679754705     4B Jun 29 10:36 test.t
like image 193
debus Avatar answered Nov 04 '25 19:11

debus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!