1

So I have a Django project which is running in Docker, which is trying to connect postgres which is running on host machine. But I am getting error

web_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1  |    Is the server running on host "localhost" (127.0.0.1) and accepting
web_1  |    TCP/IP connections on port 5432?
web_1  | could not connect to server: Cannot assign requested address
web_1  |    Is the server running on host "localhost" (::1) and accepting
web_1  |    TCP/IP connections on port 5432?

I know that we need to make postgres to listen for requests from other IP addresses. I have already made changes in postgres settings.

Added few lines in following files.

  1. /etc/postgresql/12/main/postgresql.conf

          listen_addresses = '*'
    
  2. /etc/postgresql/12/main/pg_hba.conf

         host  all  all  172.17.0.0/16  trust
    

In Django project settings.py has

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.postgresql_psycopg2',
         'NAME': 'django_docker',
         'USER': '<postgres_user>',
         'PASSWORD': '<password>',
         'HOST': 'localhost',
         'PORT': '5432',
         'ATOMIC_REQUESTS': True
     }
}

I am not sure why I am getting this error.

I also tried to use 127.0.0.1 and <public_ip> of host in Django database HOST settings, but I still get same error.

All versions

Django : 3.0.5
PostgreSQL : 12.5
Docker : 20.10.1
docker-compose : 1.25.0

I am guessing that I am missing very small thing here, but I'm not sure what it is.

Please let me know if someone has any solutions, suggestions for this. Thank you.

Ameya Joshi
  • 384
  • 1
  • 5

2 Answers2

0

localhost for a container is the container itself. You need to either create the container in host network mode (docker run --net=host ...) to be able to connect via localhost or to provide a local network IP to connect to the database (not a loopback IP like '127.0.0.1').

anemyte
  • 17,618
  • 1
  • 24
  • 45
0

After looking at many different sites and solutions, I finally found a fix for this.

This worked after I made following change in pg_hba.conf file.

Replaced

host    all     all     127.0.0.1/32     md5

with this

host    all     all      0.0.0.0/0       md5
Ameya Joshi
  • 384
  • 1
  • 5