0

I have two Spring web services which should communicate via http. Both of them are running on my machine in dcoker containers over openjdk:8-jre-alpine. Here is the POST query which fails with "Connection refused" :

public String createPost(int playerCount) {
    String uri = URI + "/create";
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri)
            .queryParam("playerCount", playerCount);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    ResponseEntity<String> response = rest.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            entity,
            String.class);
    logger.info("Create request");
    return response.getBody();
}

URI is http://localhost:8090/game Here is corresponding controller of other service:

@RequestMapping(
        path = "create",
        method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Long> create(@RequestParam("playerCount") int playerCount) {
    long gameId = gameService.create(playerCount);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    return new ResponseEntity<>(gameId, headers, HttpStatus.OK);
}

I'm simply running both containers with run -p 8080:8080 and '8090:8090' . And as I said previously getting "Connection refused" How to set up communication properly?
NOTE: it works fine if I run it with Intellij.

asap
  • 9
  • 2
  • 1
    have a look at [this SO post](https://stackoverflow.com/questions/19897743/exposing-a-port-on-a-live-docker-container) – DevDio Dec 17 '17 at 18:33

1 Answers1

0

The default Docker bridge network does not provide direct communication between containers without "links". Links have been deprecated and it's recommended to use a user defined network.

Create a user defined network for the containers and access each service via the name of the container

docker network create spring
docker run --detach --network=spring --name first -p 8080:8080 busybox \
  nc -llp 8080 0.0.0.0 -e echo first
docker run --detach --network=spring --name second -p 8090:8090 busybox \
  nc -llp 8090 0.0.0.0 -e echo second

Then you can then ping the other container or connect to a network service

# First to second
docker exec first ping second
docker exec first nc second 8090

# Second to first
docker exec second ping first
docker exec second nc first 8080

The same definition can also be done with Compose which configures the network and service names for you based on yaml config.

version: "2.1"
services:
  first:
    image: first
    ports:
      - '8080:8080'
  second:
    image: second
      - '8090:8090'
Matt
  • 68,711
  • 7
  • 155
  • 158