Docker部署Django项目时Postgres容器密码认证失败求助
Let's walk through the common issues that could be causing this password failure and fix them one by one:
1. Correct Docker Compose YAML Formatting
Your postgres service has invalid YAML syntax for env_file and expose—this is probably preventing your environment variables from being loaded properly. Update your docker-compose.yml to this:
services: web: image: 1ce04167758d #image build of webapp container command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - postgres postgres: image: postgres env_file: .env expose: - "5432"
Note: I also adjusted runserver to bind to 0.0.0.0:8000 so the service is accessible from outside the container.
2. Ensure .env File Matches Django Configuration
Create a .env file in your project root (if you don’t have one) with values that exactly match your Django DATABASES settings:
POSTGRES_USER=username POSTGRES_PASSWORD=mysecretpassword POSTGRES_DB=DBNAME
The official Postgres image will automatically create the DBNAME database and set up the user with the specified password—you no longer need to manually enter the container to create the DB or grant permissions.
3. Clean Up Conflicting Old Containers/Volumes
You previously created a standalone Postgres container named postgres—this might be conflicting with the one spun up by Docker Compose, or leftover data volumes could store old credentials. Run these commands to clean up:
# Stop and remove the old standalone Postgres container docker stop postgres docker rm postgres # Remove unused volumes to clear any stale Postgres data docker volume prune
Confirm the cleanup when prompted.
4. Add Database Readiness Check (Optional but Recommended)
depends_on only ensures the Postgres container starts before your web container—it doesn’t wait for the database to be fully ready to accept connections. Adding a quick check prevents premature connection attempts:
Update the web service's command in docker-compose.yml:
command: > sh -c "until pg_isready -h postgres -p 5432 -U username; do echo 'Waiting for Postgres to be ready...'; sleep 2; done; python manage.py runserver 0.0.0.0:8000"
Note: You’ll need postgresql-client installed in your web container image for pg_isready to work. Add this to your web app’s Dockerfile if missing:
RUN apt-get update && apt-get install -y postgresql-client
After making these changes, run docker-compose down to stop any running containers, then docker-compose up to restart everything. This should resolve the password authentication error.
内容的提问来源于stack exchange,提问作者Abhimanyu

