Running Django migrations on dockerized project

为君一笑 提交于 2019-12-11 05:05:24

问题


I have a Django project running in multiple Docker containers with help of docker-compose. The source code is attached from directory on my local machine. Here's the compose configuration file:

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

Although the application starts as it should, I can't run migrations, because every time I do manage.py makemigrations ... I receive:

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

Obviously I can open bash inside the core container and run makemigrations from there, but then the migration files are created inside the container which is very uncomfortable.

In my project's settings the database is configured as:

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

As docker postgres image is accessible at localhost:5432 I tried changing database host in settings to:

'HOST': '0.0.0.0'

But then when firing up the containers with docker-compose up I'm receiving:

...
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?
...

How should I configure database in settings.py so that Django can access it to create migrations?


回答1:


Your docker-compose configurations are not correct. You forgot to link services

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


来源:https://stackoverflow.com/questions/50552639/running-django-migrations-on-dockerized-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!