0

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 the 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```


2

1 Answer 1

0

If the container needs to connect to a host or a remote service, you need his ip or domain. Any other workaround only will work on your laptop or is just for academic purposes, not valid in the real scenarios with real users. For example: a container in aws needs to connect to an azure mysql.

In your case, you need the local ip. As I explained here https://stackoverflow.com/a/52213178/3957754 you could get the ip before the docker-compose up:

export MACHINE_HOST_IP=$(hostname -I | awk '{print $1}')
docker-compose up ...

And in your compose file use this value. For example of you have a mysql on your host and your container need it, you could use:

version: '3.2'
services:
  wordpress:
    environment:
      DB_HOST : ${MACHINE_HOST_IP}:3306
      DB_USER : usr_wordpress

Review:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.