Sowdowdow
Sowdowdow

Reputation: 439

How to expose a docker container to access host database?

I'm currently trying to figure out how to configure my docker-compose.yml to allow a web-server (django) to communicate with a PostgreSQL database running on the host machine.

The app is perfectly working outside of a container.

And now I want to create a container for better management and deployment capabilities.

I've tried this,
docker-compose.yml :

version: '3'

services:
  web:
    image: myimage
    volumes:
      - .:/appdir
    environment:
      - DB_NAME=test
      - DB_USER=test
      - DB_PASSWORD=test
      - DB_HOST=localhost
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "8000:8000"
    networks:
      - mynet
networks:
  mynet:

Dockerfile :

FROM python:3

ENV PYTHONUNBUFFERED=1 \
    DJANGO_SETTINGS_MODULE=app.settings \
    DEBUG=True \
    SECRET_KEY=akey

WORKDIR /appdir

COPY . /appdir

EXPOSE 8000

RUN pip install -r requirements.txt

But when I do so, I get the following 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?

Thanks

Upvotes: 1

Views: 2876

Answers (1)

Efrat Levitan
Efrat Levitan

Reputation: 5612

localhost is relative - inside the docker container - localhost (aka 127.0.0.1) refers to the container itself. if you want to connect to your host- give the container your host real ip as the DB_HOST.

there are many ways to find your host ip, for instance: run in your terminal hostname -I | awk '{print $1}'

Upvotes: 2

Related Questions