我在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
可以访问它以创建迁移?
答案 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