Django docker-无法翻译主机名“ db”地址:提供的节点名或服务名,或者未知 [英] Django docker - could not translate host name "db" to address: nodename nor servname provided, or not known
问题描述
我对Django和Docker还是比较陌生,并且正在遵循有关构建迷你应用程序的教程。但是,我陷入了以下错误:
I'm relatively new to Django and Docker and am following a tutorial to build a mini application. However, I'm getting stuck with the following error:
django.db.utils.OperationalError:无法将主机名 db转换为地址:提供的节点名或服务名,或者未知
我的docker-compose文件如下:
My docker-compose file looks as follows:
version: '3'
services:
db:
image: 'postgres'
ports:
- '5432'
core:
build:
context: .
dockerfile: Dockerfile
command: python3 manage.py runserver 0.0.0.0:8000
ports:
- '8000:8000'
volumes:
- .:/code
depends_on:
- db
links:
- db:db
我的settings.py文件包含数据库:
My settings.py file contains the database:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
I've seen the post here and here however both have not fixed the issue.
希望您能提供一些指导。谢谢。
Would appreciate some guidance. Thanks.
推荐答案
因此,您正在尝试从另一个容器访问在一个容器中运行的数据库?如果是的话,以下内容可能会有所帮助,至少在遇到类似问题时对我有帮助。
So you are trying to reach the db which is running in one container from another container? If yes - the following could potentially help, at least it helped me when I had similar issues.
除了定义网络之外,还应尝试定义网络配置在撰写文件中链接,创建一个具有某些名称的网络,然后在两个服务中都对其进行定义。就像此处所述,因为停靠在 链接 配置建议这样做。
Try to define networks config in addition to links in your compose file, create a network with some name and define it in both services. Like described here, as the docks on links config recommend to do that.
您的情况是这样的:
version: '3'
services:
db:
image: 'postgres'
ports:
- '5432'
networks:
some_network:
core:
build:
context: .
dockerfile: Dockerfile
command: python3 manage.py runserver 0.0.0.0:8000
ports:
- '8000:8000'
volumes:
- .:/code
depends_on:
- db
links:
- db:db
networks:
some_network:
networks:
some_network:
它帮助我解析了主机名以连接到数据库。
It helped me to resolve the host name to connect to the db.
这篇关于Django docker-无法翻译主机名“ db”地址:提供的节点名或服务名,或者未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!