在dockerized项目上运行Django迁移

时间:2018-05-27 13:27:36

标签: django postgresql docker docker-compose

我在Django的帮助下,在多个Docker容器中运行了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

虽然应用程序应该启动,但我无法运行迁移,因为每次我都会manage.py makemigrations ...收到:

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

显然我可以在bash容器中打开core并从那里运行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可以访问它以创建迁移?

1 个答案:

答案 0 :(得分:1)

您的泊坞窗组成配置不正确。你忘了链接服务

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