Spring Boot docker 微服务 restTemplate 异常

tsa*_*txt 2 resttemplate docker spring-boot

我正在尝试在 中的微服务之间rest发出请求,但出现错误。restTemplateSpring Bootdocker

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
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

看起来正确:

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

为什么不起作用?

yam*_*enk 7

Compose 中网络的官方文档中所述

网络服务到服务通信使用 CONTAINER_PORT

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

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