I receive the following error when I run python manage.py test
django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known
My docker-compose.yml looks like this:
version: '3'
services:
db:
image: postgres
ports:
- "5432:5432"
web:
entrypoint: /entrypoint.sh
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
My dockerfile looks like
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
Please give me any insight on how to resolve this issue.
It's because they are not in the same network,
You should create a network and include both db and web in it,
version: '3'
services:
db:
image: postgres
ports:
- "5432:5432"
networks:
- backend
web:
entrypoint: /entrypoint.sh
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
networks:
- backend
networks:
backend:
driver: bridge
Be careful NOT TO EXPOSE PORTS FOR THE DB .
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_PASSWORD: <password>
POSTGRES_USER: postgres
networks:
- backend
In your Django settings.py, you can now use db
as your hostname instead of localhost.
DATABASES = {'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': '<password>',
'HOST': 'db',
'PORT': '5432',
}}
Your web
service stays as it is because this one needs the container's port 8000 bound to your localhost:8000
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.