求助:使用Docker卷为何无法持久化PostgreSQL数据?
Hey there, let's work through why your PostgreSQL data keeps disappearing after container restarts—you're already on the right track using volumes, so let's narrow down the root issues.
First, Fix the Tiny (But Critical) Space in POSTGRES_DB
Looking at your docker-compose.yml, there's a leading space in your POSTGRES_DB value:
- POSTGRES_DB= hello_flask_dev #To change
This space means the actual database created is hello_flask_dev (with a leading space), not the hello_flask_dev you probably intended. If your Flask app's connection string in dev.env uses hello_flask_dev without the space, you're connecting to a default, unpersisted database instead of the one you set up the volume for.
Fix this by removing the space:
- POSTGRES_DB=hello_flask_dev #To change
Double-Check Your Database Connection String
Make sure your dev.env file's DATABASE_URL matches the corrected database name exactly. It should look like:
DATABASE_URL=postgresql://hello_flask:hello_flask@db:5432/hello_flask_dev
A mismatched name here will make it seem like data is lost, even if it's safely stored in the space-prefixed database you didn't mean to use.
Remove the Unnecessary Volume Mount for PostgreSQL
Your db service includes this volume mount:
- .:/usr/src/app #For refreshing the container if the code changes
This is completely unnecessary for a PostgreSQL container—PostgreSQL doesn't interact with your app code, and this mount can introduce permission conflicts (your host directory's permissions might not match the postgres user inside the container). Delete this line to eliminate potential issues.
Verify Volume Permissions
If the above fixes don't work, check if the pgdata volume has the correct permissions for the PostgreSQL user. Run this to view your container logs:
docker logs postgres
Look for errors like:
could not open directory "/var/lib/postgresql/data": Permission denied
If you see this, the volume's permissions are corrupted. The easiest fix (note: this will erase existing data, so only do this if you can start fresh) is to delete the old volume and recreate it:
docker-compose down -v docker-compose up -d
Docker will automatically set the correct permissions when creating a new volume for PostgreSQL.
Test Persistence
After making these changes, verify data stays put:
- Start containers:
docker-compose up -d - Connect to PostgreSQL and insert a test record
- Stop containers:
docker-compose stop - Restart containers:
docker-compose up -d - Check if the test record is still present
内容的提问来源于stack exchange,提问作者elsamarb

