How to connect from Docker container to the host?

Hello, my problem is that im trying to connect to a Docker host(Im running on Ubuntu) from a container. Ive tried several solutions including adding extra_hosts: host.docker.internal:host-gateway, but still im not able to establish the connection. Im running docker with docker-compose up.

So for example when i run script

requests.get("http//:host.docker.internal:8000") in the container then receive an error

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f18ac13dd90>: Failed to establish a new connection: [Errno 111] Connection refused')) .

This is my docker-compose.yml

version: 3.7

services:
  web:
    container_name: schedule_model_service-api
    build: .
    ports:
      - "8001:8001"
    command: startserver
    volumes:
      - ./:/app
    env_file:
      - .env
    depends_on:
      - postgres
      - redis
    extra_hosts:
    - "host.docker.internal:host-gateway"


  worker:
    container_name: schedule_model_service-worker
    build: .
    command: celeryworker
    volumes:
      - ./:/app
    env_file:
      - .env
    depends_on:
      - web
      - postgres
      - redis

  redis:
    container_name: schedule_model_service-redis
    image: redis:6.2.6
    volumes:
      - ./docker-data/redis:/var/lib/redis
    env_file:
      - .env
    restart: on-failure

  postgres:
    container_name: schedule_model_service-db
    image: postgres:14.1
    volumes:
      - ./docker-data/postgresql:/var/lib/postgresql/data
    env_file:
      - .env
    restart: on-failure
`

I solved the issue by replacing “host-gateway” by my machines local ip in the “host.docker.internal:host-gateway”

1 Like

I had roughly the same problem and was able to solve it using @dockersucks1231231231231231 's suggestion:
Docker, Ubuntu, and Apache: can ping host from container, but "Connection refused" with nc -vz - Stack Overflow.

That answer shows getting the ip address using ifconfig.