1

Hey everyone i am trying to connect my postgres database install in ubuntu 20.04 to the docker container, which will be outside of the container. I am working on django project.

I am able to create the postgres database inside the docker container and connect my django project to that database, but i want is to connect localdatabase to the django project which is running in docker container

Here is my docker-compose.yml file

version: '3.3'

services:

  # Description (For the postgres databse)
  kapediadb:
    image: postgres

    restart: always

    container_name: kapediadb
    # For accessing env data
    environment:
      - POSTGRES_DB=${DB_NAME}
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}

  # Description (For django applications)
  kapedia:

    restart: always

    container_name: kapedia

    command:
      - /bin/bash
      - -c
      - |
        python manage.py makemigrations  accounts
        python manage.py makemigrations  posts
        python manage.py makemigrations  quiz
        python manage.py migrate
        gunicorn kapedia.wsgi:application --bind 0.0.0.0:8000


    image: kapedia

    # Description (define your dockerfile location here)
    build: .

    volumes:
      - .:/kapedia

    ports:
      - "8000:8000"

    depends_on:
      -   kapediadb

    env_file:
      - .env

# Description (For volumes)
volumes:
  static:

1 Answers1

0

simply you can add this inside project container:

extra_hosts:
   - "host.docker.internal:172.17.0.1"

To find IP of docker i.e. 172.17.0.1 (in my case) you can use in local machine's terminal:

$> ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255

In postgresql.conf, change listen_addresses to listen_addresses = '*'

In pg_hba.conf, add this at the end of line

host    all             all             0.0.0.0/0               md5

Now restart postgresql service using, sudo service postgresql restart

Please use host.docker.internal hostname to connect database from Server Application.

Ex: jdbc:postgresql://host.docker.internal:5432/bankDB

Note: sudo nano /etc/postgresql/<your_version>/main/postgresql.conf use this command to open postgresql.conf file

This is the way you can connect your local database to docker-contaner

Manoj Tolagekar
  • 1,816
  • 2
  • 5
  • 22