ksclfanatic
ksclfanatic

Reputation: 142

Access docker ports from a container inside another container at localhost

I have a setup where I build 2 dockers with docker-compose.

1 container is a web application. I can access it with port 8080. Another container is ElasticSearch; it's accessible with port 9200.

This is the content of my docker-compose.yml file:

version: '3'
services:
  serverapplication:
    build: "serverapplication"
    entrypoint:
      - bash
      - -x
      - init.sh
    command: ["jdbcUrl=${jdbcUrl} dbUser=${dbUser} dbUserPassword=${dbUserPassword}"]
    ports:
      - "8080:8080"
      - "8443:8443"
      - "8787:8787"
  elasticsearch:
    build: "elasticsearch"
    environment:
      - discovery.type=single-node
    ports:
      - "9200:9200"
      - "9300:9300"

When I browse to http://localhost:8080/serverapplication I can see my server application. When I browse to http://localhost:9200/ I can see the default page of ElasticSearch.

But when I try to access ElasticSearch from inside the serverapplication, I get a "connection refused". It seems that the 9200 port is unreachable at localhost for the server application.

How can I fix this?

Upvotes: 3

Views: 5619

Answers (2)

Quinten Scheppermans
Quinten Scheppermans

Reputation: 1094

It's never safe to use localhost, since localhost means something else for your host system, for elasticsearch and for your server application. You're only able to access the containers from your host's localhost because you're mapping container ports onto your host's ports.

  1. put them in the same network
  2. give the containers a name
  3. access elasticsearch through its containername, which Docker automatically resolves to the current IP of your elasticsearch container.

Code:

version: '3'
services:
  serverapplication:
    container_name: serverapplication
    build: "serverapplication"
    entrypoint:
      - bash
      - -x
      - init.sh
    command: ["jdbcUrl=${jdbcUrl} dbUser=${dbUser} dbUserPassword=${dbUserPassword}"]
    ports:
      - "8080:8080"
      - "8443:8443"
      - "8787:8787"
    networks:
      - my-network

  elasticsearch:
    container_name: elasticsearch
    build: "elasticsearch"
    environment:
      - discovery.type=single-node
    ports:
      - "9200:9200"
      - "9300:9300"
    networks:
      - my-network

networks:
  my-network:
    driver: bridge

Upvotes: 4

Shashank V
Shashank V

Reputation: 11243

Your server application must use the host name elasticsearch to access elasticsearch service i.e., http://elasticsearch:9200

Your serverapplication and elasticsearch are running in different containers. The localhost of serverapplication is different from localhost of elasticsearch.

docker-compose sets up a network between the containers such that they can be accessed with their service names. So from your serverapplication, you must use the name 'elasticsearch' to connect to it.

Upvotes: 3

Related Questions