Docker容器通过http

时间:2017-12-17 18:30:46

标签: spring docker

我有两个Spring网络服务,应该通过http进行通信。它们都在我的机器上通过openjdk:8-jre-alpine在dcoker容器中运行。这是POST查询失败并显示“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是http://localhost:8090/game 这是其他服务的相应控制器:

@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);
}

我只是使用run -p 8080:8080和'8090:8090'运行两个容器。正如我之前所说的“拒绝连接”如何正确设置通信? 注意:如果我使用Intellij运行它可以正常工作。

1 个答案:

答案 0 :(得分:0)

default Docker bridge network不提供没有&#34;链接&#34;的容器之间的直接通信。链接已被弃用,建议使用user defined network

为容器创建user defined network并通过容器名称访问每个服务

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

然后,您可以ping另一个容器或连接到网络服务

# 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

同样的定义也可以使用Compose来完成,它根据yaml配置为您配置网络和服务名称。

version: "2.1"
services:
  first:
    image: first
    ports:
      - '8080:8080'
  second:
    image: second
      - '8090:8090'