【问题标题】:I can't connect to postgres using docker and django我无法使用 docker 和 django 连接到 postgres
【发布时间】:2022-01-27 07:54:34
【问题描述】:

这是 docker compose 文件

version: "3.8"

services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:
      - localhost
  localhost:
    image: postgres:13
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=123456
    expose:
      - "5432"      
    volumes:
      - postgres_data:/var/lib/postgresql/data/

volumes:
  postgres_data:

我在 ubuntu 20.04 系统上使用 python 3.8 映像 我已经更改了 etc/postgresql/12/main 中的文件 我收到此错误

b_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1  |    Is the server running on host "localhost" (127.0.0.1) and accepting
web_1  |    TCP/IP connections on port 5432?
web_1  | could not connect to server: Cannot assign requested address
web_1  |    Is the server running on host "localhost" (::1) and accepting
web_1  |    TCP/IP connections on port 5432?

这是我在 django 中设置的数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'dbapibanco',
        'USER': 'postgres',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

【问题讨论】:

  • 你怎么知道你没有连接?
  • 我将编辑问题并发布我遇到的错误
  • 很快@shivankgtm
  • 您正在尝试将服务命名为localhost?这显然不起作用,因为 Django 应用程序仍在将 localhost 解析为 127.0.0.1 而不是 DB 容器的 IP。您需要选择一个服务名称,该名称不是为所有操作系统上的其他用途保留的名称。
  • olá, @MarkB 我将服务名称更改为 db 并得到同样的错误

标签: python postgresql docker docker-compose


【解决方案1】:

将 python 配置文件中的 DATABASES.default.NAME 更改为 postgres。因为在创建 Postgres docker 时,默认数据库是 postgres,如果您需要使用自定义数据库名称,您应该在 Postgres 服务中使用 POSTGRES_DB 环境变量。

附注:

如果之前创建了 Postgres docker 服务,您必须使用 docker-compose down -v 删除 Postgres 数据目录,然后再次运行 docker-compose 以使用自定义数据库名称构建

version: "3.8"

services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:
      - db

  db:
    image: postgres:13
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=123456
      - POSTGRES_DB=dbapibanco
    expose:
      - "5432"      
    volumes:
      - postgres_data:/var/lib/postgresql/data/

volumes:
  postgres_data:
docker-compose down -v

docker-compose up -d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2021-06-15
    • 2022-01-25
    相关资源
    最近更新 更多