Postgres docker error “data directory “/var/lib/postgresql/data” has wrong ownership”

databasedockerlinuxpermissionspostgresql

I am trying to start a postgres container using docker

  • I have tried using multiple versions of postgres docker images
  • I have tried using volumes as mentioned here
  • tried setting POSTGRES_USER environment variable to root since root is the owner of /var/lib/postgres
  • tried using --user root but still not use

Command used to start the postgres container

docker run -d -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:15.2-alpine

Error:

data directory "/var/lib/postgresql/data" has wrong ownership

Logs:

chmod: /var/run/postgresql: Operation not permitted
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/data ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 20
selecting default shared_buffers ... 400kB
selecting default time zone ... UTC
creating configuration files ... ok
2023-04-24 21:50:29.172 UTC [53] FATAL:  data directory "/var/lib/postgresql/data" has wrong ownership
2023-04-24 21:50:29.172 UTC [53] HINT:  The server must be started by the user that owns the data directory.
child process exited with exit code 1
initdb: removing contents of data directory "/var/lib/postgresql/data"
running bootstrap script ... %  

I am using arch linux(kernel v6.2) with docker (v23)

How to resolve this error?

Best Answer

Use a named volume instead of bind volume


version: "3"
services:
  db:
    image: postgres:11.2
    environment:
      - POSTGRES_USER=test
      - POSTGRES_PASSWORD=test
      - POSTGRES_DB=test
    volumes:
      - postgres-data:/var/lib/postgresql/data
    ports:
      - "5433:5432"

Notice no slashes on the left hand side, this will create a named volume that is not mounting a location from your host system and causing the permissions to go wrong.

Related Question