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?