Django/Docker multiple containers error - could not translate host name "db" to address: Temporary failure in name resolution
I am working on creating directory and subdirectories: main project directory that contains backend and frontend code/containers. I am working on the connection of main directory and the backend first.
Here's my backend docker-compose.yml:
`services:
db:
image: postgres
volumes:
# - ./docker/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
- ./data:/var/lib/postgresql/data/
# volumes:
# - ./data:/app/backend/data
environment:
POSTGRES_DB=postgres
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
backend:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app/backend
env_file:
- docker/environment/db.env
ports:
- "8000:8000"
restart: on-failure
depends_on:
- db
links:
- db:db
Here's my backend Dockerfile:
>! `FROM python:3
>! ENV PYTHONDONTWRITEBYTECODE=1
>! ENV PYTHONUNBUFFERED=1
>! WORKDIR /app/backend/
>! COPY requirements.txt /app/backend/
>! RUN pip install -r requirements.txt
>! COPY . /app/backend/
>! EXPOSE 8000
>! CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]`
>!
>!
>! Also, here's the database settings in settings.py:
>! `DATABASES = {
>! 'default': {
>! 'ENGINE': 'django.db.backends.postgresql',
>! 'NAME': os.environ.get('POSTGRES_NAME'),
>! 'USER': os.environ.get('POSTGRES_USER'),
>! 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),
>! 'HOST': 'db',
>! 'PORT': 5432,
>! }
>! }`
My backend container works fine if I cd into backend and do a docker compose up.
I am trying to set up a docker-compose.yml from the main folder so that I can do a docker compose up from main directory and it would spin up the backend container (and later, the frontend container in the future).
Here's my docker-compose.yml for main:
`services:
backend:
build: ./backend
ports:
- "8000:8000"
# networks:
# - "backend"
# networks:
# - backend
# command: python manage.py runserver 0.0.0.0:8000
# volumes:
# - ./backend:/app/backend
# restart: always
# depends_on:
# - db
networks:
default:
ipv4_address: <ip address>
networks:
default:
driver: bridge
ipam:
config:
- subnet: <ip address>/16`
Now if I do a docker compose up from main folder, I get the following error:
What am I missing?
Tried creating a network in the docker-compose.yml for main directory.
[Update] I think I solved it.
I updated my docker-compose.yml in main folder to have a db service. Also added a db.env file so the backend service knows how to connect to db.