docker 个容器之间的 gRPC 通信

gRPC communication between docker containers

我的本地(没有 docker)很好,工作没有任何问题。

本地设置 工作正常。

Server-Jar: 运行 在 8081

Client-War: 运行 at 8000 并且可以毫无问题地连接到服务器 Jar。


DOCKER 设置 docker-compose.yml

服务器

employee:
    image: openjdk:jdk-alpine
    container_name: "employee"
    ports:
      - 9081:8080
      - 9991:9990
      - 65193:65193
    volumes:
      - ./Employee/target/Employee-1.0-SNAPSHOT-jar-with-dependencies.jar:/deployments/Employee-1.0-SNAPSHOT-jar-with-dependencies.jar
    environment:
      - JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=0.0.0.0:65193,suspend=n,server=y -Djava.net.preferIPv4Stack=true
      - GRPC_PORT=8080
    command: java -jar /deployments/Employee-1.0-SNAPSHOT-jar-with-dependencies.jar





client:
    image: jboss/wildfly
    container_name: "client"
    ports:
      - 9080:8080
      - 9990:9990
      - 65193:65193
    volumes:
      - ./Service/target/Service.war:/opt/jboss/wildfly/standalone/deployments/Service.war
    environment:
      - JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=0.0.0.0:65193,suspend=n,server=y -Djava.net.preferIPv4Stack=true
      - EMPLOYEE_HOST=localhost:9081
    command: >
      bash -c "/opt/jboss/wildfly/bin/add-user.sh admin Admin#007 --silent && /opt/jboss/wildfly/bin/standalone.sh -b 0.0.0.0 -bmanagement 0.0.0.0"
links:
  - employee
depends_on:
  - employee

员工服务器代码

Server server = ServerBuilder.forPort(Integer.parseInt(env.get("GRPC_PORT")))
        .addService(new Employee())
        .build();
try {
    server.start();
    System.out.println("Server listening at: " + env.get("GRPC_PORT"));
    server.awaitTermination();
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

客户端连接代码。

ManagedChannel channel = ManagedChannelBuilder.forTarget(env.get("EMPLOYEE_HOST")).usePlaintext().build();
EmployeeServiceGrpc.EmployeeServiceBlockingStub employee = EmployeeServiceGrpc.newBlockingStub(channel);

错误 在我进行 gRPC 调用时抛出。

Caused by: io.grpc.StatusRuntimeException: UNKNOWN at deployment.Service.war//io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:235) at deployment.Service.war//io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:216) at deployment.Service.war//io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:141)

您认为 docker 设置正确吗?如果那我可以在其他地方寻找问题

看这个人为的例子:

version: "3"

services:

  server:
    image: nginx:1.17.3
    restart: always
    container_name: nginx
    expose:
    - "80"
    ports:
    - 8888:80

  client:
    image: busybox:1.31.0
    restart: always
    depends_on:
    - server
    container_name: busybox
    command:
    - ash
    - -c
    - |
      while true;
      do
        wget --spider http://server:80 2>&1
        sleep 5s;
      done;

client 通过端口 80 访问 Nginx 容器,但它使用 server 作为主机地址来解析到适当的 (Nginx) 容器。

如果您要在 client 中将 server 替换为 localhost,客户端将尝试对自身执行 wget 命令,这将失败。

因为 server8888 发布到主机,而 Docker Compose 已启动,从主机 (!),您可以 wget http://localhost:8888 这将起作用(200).