Postgres volume mounting on WSL2 and Docker desktop: Permission Denied on PGDATA folder

Viewed 2948

There are some similar posts but this is specifically related to running Postgres with WSL2 backend on Docker desktop. WSL2 brings full Linux experience on Windows. Volumes can be mounted to both Windows and Linux file systems. But the best practice is to use Linux file system for performance reasons see docker documentation.

Performance is much higher when files are bind-mounted from the Linux filesystem, rather than remoted from the Windows host. Therefore avoid docker run -v /mnt/c/users:/users (where /mnt/c is mounted from Windows). Instead, from a Linux shell use a command like docker run -v ~/my-project:/sources where ~ is expanded by the Linux shell to $HOME.

My WSL distro is Ubuntu 20.04 LTS. I'm bind mounting Postgres data directory to a directory on Linux filesystem and I'm also configuring the Postgres PGDATA to use a sub-directory because this is instructed on the official Docker image docs:

PGDATA This optional variable can be used to define another location - like a subdirectory - for the database files. The default is /var/lib/postgresql/data. If the data volume you're using is a filesystem mountpoint (like with GCE persistent disks) or remote folder that cannot be chowned to the postgres user (like some NFS mounts), Postgres initdb recommends a subdirectory be created to contain the data.

So this is how I start Postgres with the volume mounting to WSL2 Ubuntu file system:

docker run -d \
--name some-postgres -e POSTGRES_PASSWORD=root \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v ~/custom/mount:/var/lib/postgresql/data \
postgres

I can exec into the running container and verify that the data folder exists and it's configured correctly:

enter image description here

Now from the host machine (WSL2 Linux) if I try to access that folder I get the permission denied:

enter image description here

I would appreciate if anyone can provide a solution. None of the existing posts worked to resolve the issue.

3 Answers

When you attach to the container and list the directory under /var/lib/postgresql/data it shows postgres as the owner.

Check "Arbitrary --user Notes" section in the official documentation here

The second option "bind-mount /etc/passwd read-only from the host" worked for me.

This has got nothing to do with PostgreSQL. Docker containers run as root and so any directory created by Docker will also belong to root.

Two things that were blocking us working with WSL2 on Windows were:

  1. Folder c:\Program files\WindowsApps didn't have admin account listed as owner
  2. McAfee was blocking the WSL. In order to disable blocking we had to remove following rule: Open McAfee -> Threat Prevention -> Show Advanced (button in Right upper corner) -> scroll down to Rules -> name of the rule is "Executing Subsystem for Linux"
Related