Sanewa
Sanewa

Reputation: 44

SQL Alchemy connection refused when trying to connect db and web containers

I am having problem when running docker-compose up with my django/postgres app (using sqlalchemy).

Everything is fine when just running it localy but when i try to contenerise it(with Docker) I am having an error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused. Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432`

For some reason app is not connecting to db.

My docker-compose.yml:

version: "3.9"

services:
  db:
    image: postgres:9.6
    environment:
      - POSTGRES_DB=my database
      - POSTGRES_USER=my user
      - POSTGRES_PASSWORD=my password
  web:
    build: .
    command: python3 manage.py runserver 127.0.0.1:8080
    volumes:
      - .:/code
    ports:
      - "8080:8080"
    depends_on:
      - db

My Dockerfile:

FROM python:3

ENV PYTHONUNBUFFERED=1

WORKDIR /code

COPY requirements.txt /code/

RUN pip3 install --trusted-host pypi.python.org -r requirements.txt

COPY . /code/

My engine:

engine = create_engine("postgresql://my user:my [email protected]:5432/my database")

Django settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'my database',
        'USER': 'my user',
        'PASSWORD': 'my password',
        'HOST': '127.0.0.1',
        'PORT': 5432,
    }
}

Can anyone advice where am I making mistake?

EDIT:

I tried Max's solution but nothing changed. I found out in error trackback that line where I use my engine is shown. So should I somehow modify my engine aswell?

Upvotes: 0

Views: 3574

Answers (1)

Max
Max

Reputation: 1487

I was not able to edit my comment again.

So first of all you need to combine your containers in one docker network, see here. An example docker-compose would look like that:

version: "3.9"

services:
  db:
    image: postgres:9.6
    environment:
      - POSTGRES_DB=my database
      - POSTGRES_USER=my user
      - POSTGRES_PASSWORD=my password
    networks:
      - backend

  web:
    build: .
    command: python3 manage.py runserver 127.0.0.1:8080
    volumes:
      - .:/code
    ports:
      - "8080:8080"
    depends_on:
      - db
    networks:
      - backend


networks:
  backend:
    driver: bridge
    name: backend

Then you need to edit your django settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'my database',
        'USER': 'my user',
        'PASSWORD': 'my password',
        'HOST': '<your-service-name should be "db">',
        'PORT': 5432,
    }
}

In your current settings, the django tries to connect to a database, that is running within in the same container, what is not the case.

Upvotes: 2

Related Questions