简体   繁体   English

无法与 Django 中的 Postgres 容器连接

[英]failed to connect with Postgres container in Django

django.db.utils.OperationalError: connection to server at "db" (172.18.0.2), port 5432 failed: FATAL: the database system is starting up django.db.utils.OperationalError:连接到“db”(172.18.0.2)的服务器,端口 5432 失败:致命:数据库系统正在启动

I have an issue connecting to the Postgres contaner.我在连接到 Postgres 容器时遇到问题。 I was trying in different ways like setting passwords only in the docker-compose file.我尝试了不同的方式,例如仅在 docker-compose 文件中设置密码。 Still am stuck.还是卡住了。

docker-compose.yml docker-compose.yml

version: '3'
services:
  db:
    image: postgres:alpine
    environment:
      - POSTGRES_PASSWORD=password
      - POSTGRES_USER=user
      - POSTGRES_DB=userdb
    volumes:
      - django_db:/var/lib/postgresql/data
    container_name: db
  
  singup: 
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    container_name: singup
    depends_on:
      - db 
volumes:
  django_db:

database setting数据库设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'userdb',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': 'db',
    }
}

This is a timing issue, even thought you have the below line这是一个时间问题,即使您有以下行

  singup: 
    depends_on:
      - db 

It's just waiting for db container to be up and running, not neccessarily Postgres.它只是在等待 db 容器启动并运行,而不一定是 Postgres。

To avoid this, use a tool such as wait-for-it, dockerize, sh-compatible wait-for, or RelayAndContainers template.为避免这种情况,请使用 wait-for-it、dockerize、sh-compatible wait-for 或 RelayAndContainers 模板等工具。 These are small wrapper scripts which you can include in your application's image to poll a given host and port until it's accepting TCP connections.这些是小型包装脚本,您可以将它们包含在应用程序的映像中,以轮询给定的主机和端口,直到它接受 TCP 连接。

For example, to use wait-for-it.sh or wait-for to wrap your service's command:例如,要使用 wait-for-it.sh 或 wait-for 来包装服务的命令:

  singup: 
    depends_on:
      - db
    command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"]

Repo of wait-for-it: https://github.com/vishnubob/wait-for-it等待它的回购: https://github.com/vishnubob/wait-for-it

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM