Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mount non-existing host directory into non-root container

Tags:

docker

Lets say I have a container running with a non-root user and I want to bind-mount a volume directory from the host into that container. The container then will write to that directory. Say, the directory on the host is /tmp/container/data. If that path does not exist on the host, I observe that it gets created (by docker) with ownership root. As a consequence the container is not able to write anything into that directory (access denied) because my container is not running with user root.

Of course I can take care of creating the /tmp/container/data directory with correct permissions on the host side before starting the container, but this solution obviously does not scale - I will have to do it for each and every container where I want to use a bind volume from the host for which the directory does not exist.

So my question is, what's the best way to use bind-volumes from the host for directories that do not yet exist while still let a non-root container have write access to the volume.

like image 452
Moonlit Avatar asked Jun 15 '17 18:06

Moonlit


People also ask

How do you give a non-root user in docker container access to a volume mounted on the host?

You need to run the appropriate chown and chmod commands to change the permissions of the directory. This assumes you have the runuser command available. You can accomplish pretty much the same thing using sudo instead.

How do I mount a local directory into a container?

How to Mount Local Directories using docker run -v. Using the parameter -v allows you to bind a local directory. -v or --volume allows you to mount local directories and files to your container. For example, you can start a MySQL database and mount the data directory to store the actual data in your mounted directory.


1 Answers

You accurately described the normal behavior of docker, non-existent bind mounts from the docker engine will get initialized to an empty directory owned by root. Note that this doesn't happen with swarm mode, it will fail to schedule the container on the host instead.

Options to use to avoid this include:

  • Using named volumes. These get initialized to the directory permissions in the image at that location. This is as easy as changing the full path on the host to a short name of the volume.
  • Run the container as root, and make the entrypoint fix the permissions and drop to the user before launching the application. Something similar to this is done in a jenkins-docker project I threw out on github recently.
  • Include a script in the container with permissions setuid-root which performs the chown of the directory.
like image 102
BMitch Avatar answered Sep 27 '22 19:09

BMitch