Home > OS >  Docker with Postgresql: Connection refused on localhost
Docker with Postgresql: Connection refused on localhost

Time:11-11

So, I face a really strange bug. I have a dockerized application which is already running in a live server. what I really need to do now is to make ti work locally and the only thing I am getting is this error: django.db.utils.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?

This is my docker-compose.yml file:

version: "3"
services:
#
backend:
  build:
    context: diabetesmelitusbackend
     args:
      - DATABASE_ENGINE=${DATABASE_ENGINE}
      - DATABASE_NAME=${DATABASE_NAME}
      - DATABASE_HOST=${DATABASE_HOST}
      - DATABASE_USER=${DATABASE_USER}
      - DATABASE_PASSWORD=${DATABASE_PASSWORD}
      - DATABASE_PORT=${DATABASE_PORT}
      - DJANGO_SUPERUSER_USERNAME=${DJANGO_SUPERUSER_USERNAME}
      - DJANGO_SUPERUSER_EMAIL=${DJANGO_SUPERUSER_EMAIL}
      - DJANGO_SUPERUSER_PASSWORD=${DJANGO_SUPERUSER_PASSWORD}
  image: backend
  ports:
    - "9000:9000"
  extra_hosts:
    - "host.docker.internal:127.0.0.1"

and this is my .env file

DATABASE_ENGINE=django.db.backends.postgresql
DATABASE_NAME=db_name
DATABASE_HOST=db
DATABASE_USER=db_user
DATABASE_PASSWORD=1234
DATABASE_PORT=5432 
DJANGO_SUPERUSER_USERNAME=admin
[email protected] 
DJANGO_SUPERUSER_PASSWORD=1234

Build is working fine but the up in localhost is returning the error about the connection. Any ideas?

On the .env file, I have tried to replace DATABASE_HOST with localhost, 127.0.0.1 and still nothing. Also I have allowed listen_addresses = '*' and I have added the localhost to pg_hba.conf file

CodePudding user response:

So finally I got what was wrong (at least on Ubuntu 20) On the .env file, on the DATABASE_HOST I was putting the localhost (or 127.0.0.1) which indeed is the localhost of the container. In order to make it connect to my machine's localhost, I had to put this IP 172.17.0.1.

The extra_hosts of the docker-compose.yml file didn't really matter.

CodePudding user response:

It's better practice to run your database in a container

  • Related