Vale Tolpegin
Vale Tolpegin

Reputation: 77

Cannot connect to remote PostgreSQL instance from Django app running within Docker container

I am trying to connect a Django app running inside of a docker container to a PostgreSQL database running on another computer (lets say with an IP address of 192.168.1.22). Thus far in my experimentation, I always get the following error when attempting to connect to the PostgreSQL instance from a docker container (my code works fine outside of the docker container):

Is the server running on host "127.0.0.1" and accepting
 TCP/IP connections on port 5432?

I've made sure that I allow all inbound connections to the PostgreSQL database (by changing the config file for my PostgreSQL server as recommended here.

Here is my settings code in my Django app for the database connection:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'xxxxx',
        'USER': 'xxxxxxx',
        'PASSWORD': 'xxxxxxxxxxx',
        'HOST': '192.168.1.22',
        'PORT': '5432',
    }
}

Here is my Dockerfile:

FROM python:3.6
ENV PYTHONUNBUFFERED 1

# Install dependencies
RUN mkdir /config
ADD /config/requirements.pip /config/
RUN pip install -r /config/requirements.pip

# Install source code
RUN mkdir /src
WORKDIR /src
COPY ./src/ /src/

ENV UWSGI_WSGI_FILE=/src/xxxxxxxxx/wsgi.py UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_WORKERS=2 UWSGI_THREADS=8 UWSGI_UID=1000 UWSGI_GID=2000 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy

RUN python /src/manage.py collectstatic --noinput

EXPOSE 8000

CMD ["uwsgi", "--http-auto-chunked", "--http-keepalive"]

Here is the script I use to build (& run) my docker container:

#!/bin/bash

docker build .

docker run -i -t -p 8000:8000 xxxx/xxxxxxx

I've also tried using the add-host option for Docker to add the database as a host, then reference the host name from within the settings file of my project. In all scenarios I end up with the same error above.

Thank you for the help in advance!

Upvotes: 3

Views: 1559

Answers (1)

williamcabrera4
williamcabrera4

Reputation: 270

I fix this problem using extra_hosts and Docker-compose

For example

web:
image: my-web-app
build: .
command: bash -c "uwsgi --http-auto-chunked --http-keepalive"
ports:
  - "8000:8000"
extra_hosts:
  - "postgresql:192.168.1.22"

In your Django configuration

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': 'xxxxx',
    'USER': 'xxxxxxx',
    'PASSWORD': 'xxxxxxxxxxx',
    'HOST': 'postgresql',
    'PORT': '5432',
}

To run your app use docker-compose up

Upvotes: 2

Related Questions