Persist data on postgres docker with a volume when restarting the container

Viewed 6630

I have read stackoverflow posts, but could not find a solution to my problem of persisting data with a volume with postgres:

First i create a volume:

docker volume create pgdata

Then i run the postgres container:

docker run -d -v pgdata:/var/lib/postgresql -e POSTGRES_PASSWORD=password -p 5432:5432 postgres

Then i create a database connecting with sql:

psql postgresql://postgres:password@localhost:5432/postgres

After stopping the container i restart with:

docker run -d -v pgdata:/var/lib/postgresql -e POSTGRES_PASSWORD=password -p 5432:5432 postgres

The database is lost. Should it not stay there, because i use the same volume?

EDIT: PGDATA="/var/lib/postgresql/data/pgdata" needs to be added and it works as well as the solution of David Maze

1 Answers

Inside the postgres image, the PostgreSQL data directory is /var/lib/postgresql/data. Unless you mount your volume on exactly this path, it won't get used.

docker run -d \
  -v pgdata:/var/lib/postgresql/data \ # <-- add .../data
  -e POSTGRES_PASSWORD=password \
  -p 5432:5432 \
  postgres

At a technical level, this is because the Dockerfile declares VOLUME /var/lib/postgresql/data. If nothing else is mounted on that exact path, this causes Docker to create an anonymous volume at docker run time and store the data there. Since you're mounting a volume on the parent directory but not the exact path, this triggers the anonymous-volume case.

Related