4

I have a django project with PostgreS database. I need to use my local database in docker container. How to share localhost of the machine with docker container? My docker-compose.yml :

  version: '3'
  services:
    web:
      build: ./
      network_mode: "host"
      command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput --i rest_framework && gunicorn orion-amr.wsgi:application --bind 0.0.0.0:8000 --workers=2"
      ports:
        - "${webport}:8000"
        - "${pgport}:${pgport}"
      env_file:
        - ./.env

Django settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': os.environ.get('pgdatabase'),
        'USER': os.environ.get('pguser'),
        'PASSWORD': os.environ.get('pgpassword'),
        'HOST': os.environ.get('pghostname'),
        'PORT': os.environ.get('pgport'),
    }
}

I added

listen_addresses = '*'  

to postgresql.conf file and below is my pg_hba.conf file:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             0.0.0.0/0               trust
# IPv6 local connections:
host    all             all             ::/0                    trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust

Now I have an error:

web_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1  |        Is the server running on host "127.0.0.1" and accepting
web_1  |        TCP/IP connections on port 5432?
web_1  |

Who can help me? Please!

Aigerim Sadir
  • 353
  • 5
  • 18

1 Answers1

8

seems like os.environ.get('pghostname') pointing to 127.0.0.1 where 127.0.0.1 mean this container, not the Host DB. As the error

Is the server running on host "127.0.0.1" and accepting

To connect with host DB you have special DNS for mac and window host.docker.internal. DB host should be

'HOST': "host.docker.internal"

To connect with HOST DB, or if you are on Linux then it should be

'HOST': "HOST_IP"

You can get host IP from ifconfig.

Adiii
  • 54,482
  • 7
  • 145
  • 148