2

When creating a container using docker run, is there a way to automatically copy files from a docker volume to the host directory it is mounted on?

When running

docker run -d -v /localpath:containerpath image 

the files found in containerpath are not copied to my /localpath directory.

Is there a way to achieve this? The image contains a directory that needs to be accessible on the host machine for local development.

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
Adrian
  • 51
  • 1
  • 5
  • 1
    Option -v allows to declare a shared volume between the local host and the container, of the shots each file created via local hsot or via the container will be visible to the other. – andolsi zied Nov 25 '16 at 14:30
  • Possibly related: http://stackoverflow.com/questions/36107442/mount-docker-host-volume-but-overwrite-with-containers-contents – nwinkler Nov 25 '16 at 14:33
  • Easy: add a script to do the copying work in any way you desire. Append a line to invoke the script in .bash_profile, or your system's equivalent. – Software Engineer Nov 25 '16 at 14:41
  • 2
    Hard: explain why you want to do this – Software Engineer Nov 25 '16 at 14:42
  • What i am trying to do is for each web development project we have at our company automatically generate a docker image with an environment that emulates the one we are running live. The image clones the specific project repo on build and exposes the host public_html directory to a volume, loads the sql dump + assets from live and exposes a volume with the directory so all the developer has to do is run the container on his local machine and everything would be set up for him to start coding. But for this, the volume files would need to be copied to the directory he sets up the volume in – Adrian Nov 25 '16 at 17:00
  • In that case: Change the image's start command to copy the files to the mapped directory and then start the server. Something like `./copyFiles.sh && ./startServer.sh` – nwinkler Nov 26 '16 at 09:34

1 Answers1

3

What i did not know was that when adding a file to a volume from the shell of the container, it is also created in the host directory. So after a lot of debugging and testing things i have managed to achieve what i wanted

For clarification if anyone needs this in the future: to automatically generate a docker container that clones a git repo and expose the host public_html directory to a volume with the files already copied to the host ready for editing

# Create Volume for the directory
VOLUME /var/www/html

COPY scripts/start.sh /start.sh
RUN chmod -v +x /start.sh
CMD ["/start.sh"]

start.sh contains the code to clone the repo if the directory is empty

#!/bin/bash
if [ "$(ls -A /var/www/html)" ]; then
echo "Directory already cloned"
else
echo "Repo files do not exist" ;
git clone ...
fi

Thanks for the help

Adrian
  • 51
  • 1
  • 5