Reputation: 71
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. I'm trying to use PostgreSQL with Django and Wagtail as its CMS
My docker-compose.yml looks like:
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:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
Am I missing anything?
Upvotes: 1
Views: 10230
Reputation: 814
In my situation both db
and localhost
did not work. So I set settings.py
to:
DATABASES = {
"default": {
...
'HOST': 'host.docker.internal',
...
}
}
Which allows one docker container to access all other containers similar to localhost. Source of idea: https://stackoverflow.com/a/62147846/7924573
Upvotes: 1
Reputation: 159750
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. If you add ports: [5432:5432]
to the database configuration in the docker-compose.yml
file, the database will be accessible via (probably) localhost
. On the other hand, when you run docker-compose up
, the application runs inside Docker and the database will be reachable at 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
).
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
...
Upvotes: 2