Reputation: 695
django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5432?
docker-compose
version: '3.9'
services:
backend:
build: ./backend
command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
volumes:
- ./backend:/app/backend
ports:
- "8000:8000"
env_file:
- backend/.env.dev
depends_on:
- db
db:
image: postgres:14-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
ports:
- "5432:5432"
env_file:
- backend/.env.dev
volumes:
postgres_data:
Dockerfile:
FROM python:3.9.10-alpine
ENV PYTHONUNBUFFERED 1
WORKDIR /app/backend
COPY requirements.txt /app/backend
RUN pip install --upgrade pip
RUN apk add --update --no-cache postgresql-client
RUN apk add --update --no-cache --virtual .tmp-build-deps \
gcc libc-dev linux-headers postgresql-dev
RUN pip install -r requirements.txt
RUN apk del .tmp-build-deps
EXPOSE 8000
CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"]
Database setting:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": os.environ.get("POSTGRES_DB"),
"USER": os.environ.get("POSTGRES_USER"),
"PASSWORD": os.environ.get("POSTGRES_PASSWORD"),
"HOST": os.environ.get("POSTGRES_HOST"),
"PORT": 5432,
}
}
.env :
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=my_db
POSTGRES_HOST=db
Upvotes: 1
Views: 4844
Reputation: 9
I also faced this issue. I was using docker version 20.10.12 and then upgraded docker-compose to v2.4.1. After restarting my system the build was working fine.
Upvotes: 0
Reputation: 52
docker-compose.yml
:
version: 3.9
services:
backend:
build: ./backend
command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
volumes:
- ./backend:/app/backend
networks:
- backend
ports:
- "8000:8000"
env_file:
- backend/.env.dev
depends_on:
- db
db:
image: postgres:14-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
ports:
- "5432:5432"
networks:
- backend
env_file:
- backend/.env.dev
volumes:
postgres_data:
networks:
backend:
driver: bridge
I added network
. see this link
I guess it work.
Upvotes: 1
Reputation: 210
Are you running Django on your local machine or inside of the docker?
If you're trying to run it on your local machine, just use localhost
instead of the container name db
for your POSTGRES_HOST
env variable.
But, I'm not sure about the exact reason. Can you share the logs via docker logs backend
and docker logs db
?
Upvotes: -1