Option A, host bind mount
best for direct host access and backups
- Mount a host directory to the container’s data dir (usually /var/lib/postgresql/data)
- Pros: you can back up/edit files directly on the host; easy to inspect.
- Cons: host permission must align with the postgre user inside the container; slightly more OS-specific concerns.
Example(Linxu):
- Prepare host dir: mkdir -p /host/postgre-data; chwon 999:999 /host/postgre-data
- Run: docker run –name my-postgres -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb -v /host/postgres-data:/var/lib/postgresql/data -p 5432:5432 -d postgres:15
Option B, Docker named volume
best for Docker lifecycle management
- Use a named volume to store data (still persists beyond container life; data lives on the host, but managed by Docker)
- Pros: easier to manage, fewer permission issues, better protability.
- Cons: you don’t directly browse host files unless you inspect the volume.
Example:
- Create and run:
- docker volume create pgdata
- docker run –name my-postgres -e POSTGRES_PASSWORD=secret -e -v pgdata:/var/lib/postgresql -p 5432:5432 -d postgres:15
Where data is stored on host:
docker volume inspect pgdata
Create a database: