0

How do I get my two docker containers to communicate with each other on Localhost?

I have separated out my project into a backend and a front-end. I am now trying to run both parts in separate docker containers however i get a connection refused. I tried running both on a docker network but it didn't seem to work.

Both my Dockerfiles look like


COPY ./build/libs/demo-0.0.1-SNAPSHOT.jar /usr/app/

WORKDIR /usr/app

RUN sh -c 'touch demo-0.0.1-SNAPSHOT.jar'

RUN apk add --update \
    curl \
    && rm -rf /var/cache/apk/*

ENTRYPOINT ["java","-jar","demo-0.0.1-SNAPSHOT.jar"]

and the front end makes calls to the back end by

protected <T> ResponseEntity<T> getRequest(String path, Class<T> responseType) {
        return restTemplate.getForEntity("http://localhost:8090/" + path, responseType);
    }

but i get a

java.net.ConnectException: Connection refused (Connection refused)

I run both my container via:

docker run -p 8090:8090 -d repo/back-end
docker run -p 8080:8080 -d repo/front-end   
BeerEye
  • 59
  • 2
  • 6
  • 2
    Use docker compose. Create a network. Refer to containers by name. They are definitely **not** localhost. – Boris the Spider Mar 30 '19 at 15:06
  • Possible duplicate of [In docker-compose how to create an alias / link to localhost?](https://stackoverflow.com/questions/43579740/in-docker-compose-how-to-create-an-alias-link-to-localhost) – David Maze Mar 30 '19 at 15:34

2 Answers2

0

In docker you can create your own network:

docker network create myNetwork

And run containers inside this network using --net and --name flags:

docker run -d -p 8000:8000 --net myNetwork --name backend backend-image
docker run -d -p 8001:8001 --net myNetwork frontend-image

Then you should be able to access backend using http://backend:8000 url from your frontend container.

baza92
  • 344
  • 1
  • 10
0

Thanks both for the responses, i added a docker-compose.yml in frontend

version: '3'
services:
  frontend:
    build: .
    ports:
      - "8080:8080"
networks:
  default:
    external:
      name: myNetwork

and in backend

version: '3'
services:
  backend:
    build: .
    ports:
      - "8090:8090"
networks:
  default:
    external:
      name: myNetwork

and then changed my rest service to make calls to

private static final String prefix = "http://backend:8090/";
BeerEye
  • 59
  • 2
  • 6
  • 1
    The point of `docker-compose` is to **compose** sets of containers. Having a separate file for each container rather misses this point. – Boris the Spider Mar 30 '19 at 18:52
  • If I have both parts stored in a separate repo, how could this be achieved using only one compose file? – BeerEye Mar 30 '19 at 22:23
  • That same way it works with Java libraries. Push the two separate containers up to a repository and then pull them down in a third project. – Boris the Spider Mar 31 '19 at 07:39