You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Docker卷为何无法持久化PostgreSQL数据?

Troubleshooting PostgreSQL Data Persistence in Docker Compose

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:

  1. Start containers: docker-compose up -d
  2. Connect to PostgreSQL and insert a test record
  3. Stop containers: docker-compose stop
  4. Restart containers: docker-compose up -d
  5. Check if the test record is still present

内容的提问来源于stack exchange,提问作者elsamarb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:08:14