Running Django migrations on dockerized project

2019-08-19 02:03发布

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条回答
Bombasti
2楼-- · 2019-08-19 02:47

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
查看更多
登录 后发表回答