【问题标题】:Running Django migrations on dockerized project在 dockerized 项目上运行 Django 迁移
【发布时间】:2018-11-06 05:41:07
【问题描述】:

docker-compose 的帮助下,我有一个Django 项目在多个Docker 容器中运行。源代码附在我本地机器上的目录中。这是撰写配置文件:

version: '3'
services:
  db:
    image: 'postgres'
    ports:
      - '5432:5432'
  core:
    build:
      context: .
      dockerfile: Dockerfile
    command: python3 manage.py runserver 0.0.0.0:8000
    ports:
      - '8001:8000'
    volumes:
      - .:/code
    depends_on:
      - db

尽管应用程序正常启动,但我无法运行迁移,因为每次执行manage.py makemigrations ... 我都会收到:

django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known

显然我可以在core 容器内打开bash 并从那里运行makemigrations,但是随后在容器内创建了迁移文件,这非常不舒服。

在我的项目设置中,数据库配置为:

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

由于可以通过localhost:5432 访问 docker postgres 图像,我尝试将设置中的数据库主机更改为:

'HOST': '0.0.0.0'

但是当我用docker-compose up 启动容器时,我收到了:

...
django.db.utils.OperationalError: could not connect to server: 
Connection refused
Is the server running on host "0.0.0.0" and accepting
TCP/IP connections on port 5432?
...

我应该如何在settings.py 中配置数据库,以便Django 可以访问它来创建迁移?

【问题讨论】:

    标签: django postgresql docker docker-compose


    【解决方案1】:

    您的 docker-compose 配置不正确。您忘记关联服务了

    version: '3'
    services:
      db:
        image: 'postgres'
        ports:
          - '5432:5432'
      core:
        build:
          context: .
          dockerfile: Dockerfile
        command: python3 manage.py runserver 0.0.0.0:8000
        ports:
          - '8001:8000'
        volumes:
          - .:/code
        depends_on:
          - db
        links: # <- here
          - db
    

    【讨论】:

    • 我遇到了和之前一样的错误:django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known
    • @StanRedoute 更新配置后您是否重新启动了容器? docker-compose down &amp;&amp; docker compose up。这应该有效,如果仍然无效,我们需要更多信息
    • 我已经用 --no-cache 重建了 compose 以进行干净的构建,并在启动 compose up 期间收到:django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 5432? 看起来 links 成功了,但 Django 本身无法访问到 db 的链接?
    • @StanRedoute 这意味着您的后端在db 容器准备就绪之前就已启动,在docs.docker.com/compose/startup-order 中阅读有关此问题的更多信息
    猜你喜欢
    • 2018-07-20
    • 2020-08-07
    • 1970-01-01
    • 2021-06-13
    • 2021-06-23
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多