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

Docker部署Django项目时Postgres容器密码认证失败求助

Fixing Django-Postgres Password Authentication Error in Docker Compose

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.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:47:44