elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fab5b67c950>: Failed to establish a new connection: [Errno 111] Connection refuse

Hello ,

I am trying to connect to Elasticsearch using docker but I keep getting connection refused error while elasticsearch is running on localhost:9200

This is my docker-compose file

version: '3.8'

services:
  api:
    container_name: api
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    depends_on:
      - elasticsearch
    environment:
      - ELASTICSEARCH_URL=http://elasticsearch:9200
    networks:
      - elasticnet

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.10.0
    container_name: elasticsearch
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - discovery.type=single-node
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.security.enabled=false
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - esdata1:/usr/share/elasticsearch/data
    ports:
      - "9200:9200"
    networks:
      - elasticnet

  kibana:
    image: docker.elastic.co/kibana/kibana:7.10.0
    container_name: kibana
    depends_on:
      - elasticsearch
    environment:
      - ELASTICSEARCH_URL=http://elasticsearch:9200
      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
    ports:
      - "5601:5601"
    networks:
      - elasticnet

networks:
  elasticnet:

volumes:
  esdata1:

I am initiating Elasticsearch like this

from elasticsearch import Elasticsearch

class ElasticsearchClient:
    client = None

    @classmethod
    def get_instance(self):
        if self.client is None:
            self.client = Elasticsearch("http://elasticsearch:9200")
            print("Connected to Elasticsearch!", self.client.info())
        return self.client

Can anyone tell me what the problem is ?

Hello! The problem here is the docker compose, Elasticsearch is exposed on port 9200, so mapping internal port 8000 to external 8000 does nothing in this case, ports should be "9200:9200".

What happens if you open to http://localhost:9200 in your web browser while the docker compose containers are up?