donglu8779 2018-07-18 01:24
浏览 229

尝试使用grpc连接到Docker容器时出错

I try to connect to a docker container using golang grpc but run into the following problem. OS I use is Linux.

My .proto file appears like this:

syntax = "proto3"; 
package reverse;
service Reverse {
    rpc Do(Request) returns (Response) {}
}
message Request {
    string message = 1;
}
message Response {
    string message = 1;
}

Client main.go:

func main() {
    opts := []grpc.DialOption{
        grpc.WithInsecure(),
        grpc.WithBlock(),
    }
    args := os.Args
    conn, err := grpc.Dial("127.0.0.1:5300", opts...)
    if err != nil {
        grpclog.Fatalf("fail to dial: %v", err)
    }
    defer conn.Close()
    log.Info("Connect finished")
    client := pb.NewReverseClient(conn)
    request := &pb.Request{
        Message: args[1],
    }
    response, err := client.Do(context.Background(), request)
    if err != nil {
        grpclog.Fatalf("fail to dial: %v", err)
    }
    fmt.Println(response.Message)
}

Server main.go:

func main() {
    listener, err := net.Listen("tcp", ":5300")
    if err != nil {
        grpclog.Fatalf("failed to listen: %v", err)
    }
    opts := []grpc.ServerOption{}
    grpcServer := grpc.NewServer(opts...)
    pb.RegisterReverseServer(grpcServer, &server{})
    grpcServer.Serve(listener)
}
type server struct{}
func (s *server) Do(c context.Context, request *pb.Request) (response *pb.Response, err error) {
    n := 0
    rune := make([]rune, len(request.Message))
    for _, r := range request.Message {
        rune[n] = r
        n++
    }
    rune = rune[0:n]
    for i := 0; i < n/2; i++ {
        rune[i], rune[n-1-i] = rune[n-1-i], rune[i]
    }
    output := string(rune)
    response = &pb.Response{
        Message: output,
    }
    return response, nil    
}

It is expected that the client can receive the reverse of the string passed by command line argument. This works fine, and I try to pack the server into a docker image. Dockerfile:

FROM scratch
ADD . /bin/
ENTRYPOINT ["/bin/server"]
EXPOSE 5300

Here is my problem: When I run the docker container with argument -p 5300:5300 then the correct value can be returned. Now I run the container without port mapping. I find the container's IP address by docker inspect and its address is 172.17.0.2. Then I change the IP address in grpc.Dial function in Client main.go to 172.17.0.2. I run the client again and find the program is stuck at client.Do function. So what I want to ask is that how can I connect to docker container using direct IP address?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
    • ¥50 树莓派安卓APK系统签名
    • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
    • ¥65 汇编语言除法溢出问题
    • ¥15 Visual Studio问题
    • ¥20 求一个html代码,有偿
    • ¥100 关于使用MATLAB中copularnd函数的问题
    • ¥20 在虚拟机的pycharm上
    • ¥15 jupyterthemes 设置完毕后没有效果
    • ¥15 matlab图像高斯低通滤波