'Docker not starting, volume permission denied error

i am trying create postgresql container with this command in windows with WSL 2 integration enabled

docker run -d --name pg-docker --restart=always --publish 5432:5432 \
  -e POSTGRES_PASSWORD=postgres \
  -v "C:\Program Files\Docker\Volumes\pg:/var/lib/postgresql/data" \
 postgres:alpine

but container not starting, keeps restarting and I get permission error:

chmod: /var/lib/postgresql/data: Permission denied.

i tried to change chmod permissions but I cant enter bash due to container not running



Solution 1:[1]

Use extreme caution with these options. Bind-mounting a system directory such as /home or /usr with the Z option renders your host machine inoperable and you may need to relabel the host machine files by hand.

Use the below command as it worked well for me.

docker run -d --name pg-docker --restart=always \
  --publish 5432:5432 -e POSTGRES_PASSWORD=postgres \
  -v "C:\Program Files\Docker\Volumes\pg:/var/lib/postgresql/data:Z" \
  postgres:alpine

Reason: Host volume settings are not portable, since they are host-dependent and might not work on any other machine. Also, be aware that the host system has no knowledge of container SELinux policy. Therefore, if SELinux policy is enforced, the mounted host directory is not writable to the container.

Work around this by assigning the proper SELinux policy type to the host directory:

chcon -Rt svirt_sandbox_file_t host_dir

Where host_dir is a path to the directory on host system that is mounted to the container.

The above command (with :Z) will automatically do the chcon -Rt svirt_sandbox_file_t /var/lib/postgresql/data

See https://docs.docker.com/storage/bind-mounts/#configure-the-selinux-label

Source: Permission denied on accessing host directory in Docker

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 Brian Burns