'Docker mounting volume. Permission denied

I have a problem with creating new files in mounted docker volume.

Firstly after installation docker i added my user to docker group.

sudo usermod -aG docker $USER

Created as my $USER folder:

mkdir -p /srv/redis

And starting container:

docker run -d -v /srv/redis:/data --name myredis redis

when i want to create file in /srv/redis as a user which created container I have a problem with access.

mkdir /srv/redis/redisTest
mkdir: cannot create directory ‘/srv/redis/redisTest’: Permission denied

I tried to search in other threads but i didn't find appropriate solution.



Solution 1:[1]

The question title does not reflect the real problem in my opinion.

mkdir /srv/redis/redisTest
mkdir: cannot create directory ‘/srv/redis/redisTest’: Permission denied

This problem occurs very likely because when you run:

docker run -d -v /srv/redis:/data --name myredis redis

the directory /srv/redis ownership changes to root. You can check that by

ls -lah /srv/redis

This is normal consequence of mounting external directory to docker. To regain access you have to run

sudo chown -R $USER /srv/redis

Solution 2:[2]

I think /srv/redis/redisTest directory is created by user inside redis container, so it belong to redis container user.

Have you already check using ls -l to see that /srv/redis/redisTest directory belong to $USER?

Solution 3:[3]

This could also be related (as I just found out) to having SELinux activated. This answer on the DevOps Stack Exchange worked for me:

The solution is to simply append a :z to the [docker] run volume argument so that this:

docker run -v /host/foobar:/src_dir /bin/bash

becomes this:

docker run -it -v /host/foobar:/src_dir:z /bin/bash

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stbnrivas
Solution 2 kenorb
Solution 3 Dologan