title: Postgres volume mounting on WSL2 and Docker desktop: Permission Denied on PGDATA folder
body: <p>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 <a href="https://docs.docker.com/docker-for-windows/wsl/" rel="nofollow noreferrer">docker documentation</a>.</p>
  <blockquote>
  <p>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.</p>
  </blockquote>
  <p>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:</p>
  <blockquote>
  <p>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.</p>
  </blockquote>
  <p>So this is how I start Postgres with the volume mounting to WSL2 Ubuntu file system:</p>
  <pre><code>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
  </code></pre>
  <p>I can exec into the running container and verify that the data folder exists and it's configured correctly:</p>
  <p><a href="https://i.stack.imgur.com/RJeF4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJeF4.png" alt="enter image description here" /></a></p>
  <p>Now from the host machine (WSL2 Linux) if I try to access that folder I get the permission denied:</p>
  <p><a href="https://i.stack.imgur.com/oj6Y2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oj6Y2.png" alt="enter image description here" /></a></p>
  <p>I would appreciate if anyone can provide a solution. None of the existing posts worked to resolve the issue.</p>