Spring 启动 docker 微服务 restTemplate 异常

Spring Boot docker microservices restTemplate exception

我正在尝试通过 restTemplatedocker 中的 Spring Boot 微服务之间发出 rest 请求,但出现错误。

docker-compose.yml:

  api:
    image: api-service
    container_name: api-service
    restart: always
    depends_on:
      - product
    ports:
      - 8081:8080
    links:
      - product:product
    environment:
      - SERVICE_PORT_PRODUCT=8083

  product:
    image: product-service
    container_name: product-service
    restart: always
    ports:
      - 8083:8080

Exception 日志:

ERROR 1 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://product:8083/api/products/": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)] with root cause
java.net.ConnectException: Connection refused (Connection refused)

看起来正确:

POST 请求“http://product:8083/api/products/

为什么不起作用?

Networking in Compose

的官方文档中所述

Networked service-to-service communication use the CONTAINER_PORT

因此当你想从一个容器向另一个容器发出请求时,你需要使用容器端口而不是主机端口。

请求应该是:http://product:8080/api/products/ 从 api 容器到产品容器。