[英]could not translate host name to “db” to address: Unknown host
I'm attempting to follow the guide provided by: https://docs.docker.com/compose/django/ Whenever I attempt to makemigrations, it gives me the Unknown host error given in the title.我正在尝试遵循以下提供的指南: https://docs.docker.com/compose/django/每当我尝试进行迁移时,它都会给我标题中给出的未知主机错误。 I'm trying to use PostgreSQL with Django and Wagtail as its CMS
我正在尝试使用 PostgreSQL 和 Django 和 Wagtail 作为其 CMS
My docker-compose.yml looks like:我的 docker-compose.yml 看起来像:
version: "3.9"
services:
db:
image: postgres
environment:
- POSTGRES_DB=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
and my settings in the settings.py file look like:我在 settings.py 文件中的设置如下所示:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
Am I missing anything?我错过了什么吗?
Your code can run in two different environments, and hard-coding the connection information might not be correct.您的代码可以在两种不同的环境中运行,并且硬编码连接信息可能不正确。
You mention in a comment that you're running something like:您在评论中提到您正在运行以下内容:
docker-compose up -d db
python manage.py makemigrations
In this environment python
is running outside of Docker.在此环境中,python 在
python
之外运行。 If you add ports: [5432:5432]
to the database configuration in the docker-compose.yml
file, the database will be accessible via (probably) localhost
.如果在
docker-compose.yml
文件中的数据库配置中添加ports: [5432:5432]
,则可以通过(可能) localhost
访问数据库。 On the other hand, when you run docker-compose up
, the application runs inside Docker and the database will be reachable at db
.另一方面,当您运行
docker-compose up
,应用程序在 Docker 内部运行,并且可以在db
访问数据库。
You can use an environment variable to configure this.您可以使用环境变量来配置它。 I find it useful to give these variables default values that would be useful for a developer, and set them to different values in my deployment setup (the
docker-compose.yml
).我发现为这些变量提供对开发人员有用的默认值很有用,并在我的部署设置(
docker-compose.yml
)中将它们设置为不同的值。
DATABASES = {
'default': {
...
'HOST': os.getenv('DB_HOST', 'localhost'),
...
}
}
version: "3.9"
services:
db:
ports:
- '5432:5432' # makes this accessible from your development environment
...
web:
environment:
- DB_HOST=db
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.