MeWrite Docs

gRPC: UNAVAILABLE - Connection refused

gRPCサーバーに接続できない場合のエラー原因と解決策

概要

gRPCクライアントがサーバーに接続できない場合に発生するエラーです。

エラーメッセージ

``` rpc error: code = Unavailable desc = connection error: desc = “transport: Error while dialing dial tcp 127.0.0.1:50051: connect: connection refused” ```

原因

  1. サーバーが起動していない: プロセスが停止
  2. ポート番号の不一致: クライアントとサーバーで異なるポート
  3. ネットワーク到達不能: ファイアウォールやセキュリティグループ
  4. TLS設定の不一致: 暗号化設定の違い

解決策

1. サーバーの状態を確認

```bash

プロセス確認

ps aux | grep grpc

ポート確認

lsof -i :50051 netstat -an | grep 50051 ```

2. クライアント設定を確認

```go // Go conn, err := grpc.Dial( “localhost:50051”, grpc.WithTransportCredentials(insecure.NewCredentials()), )

// または TLS付き creds, _ := credentials.NewClientTLSFromFile(“server.crt”, “”) conn, err := grpc.Dial(“localhost:50051”, grpc.WithTransportCredentials(creds)) ```

```python

Python

channel = grpc.insecure_channel(’localhost:50051')

TLS付き

credentials = grpc.ssl_channel_credentials(open(‘server.crt’, ‘rb’).read()) channel = grpc.secure_channel(’localhost:50051’, credentials) ```

3. リトライロジックを追加

```go // Go でリトライ設定 retryPolicy := `{ “methodConfig”: [{ “name”: [{“service”: “myservice”}], “retryPolicy”: { “MaxAttempts”: 4, “InitialBackoff”: “.1s”, “MaxBackoff”: “1s”, “BackoffMultiplier”: 2, “RetryableStatusCodes”: [“UNAVAILABLE”] } }] }`

conn, err := grpc.Dial( address, grpc.WithDefaultServiceConfig(retryPolicy), ) ```

4. ヘルスチェックを実装

```go // サーバー側 import “google.golang.org/grpc/health” import “google.golang.org/grpc/health/grpc_health_v1”

healthServer := health.NewServer() grpc_health_v1.RegisterHealthServer(s, healthServer) healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING) ```

よくある間違い

  • insecure と secure の混在
  • ホスト名解決の問題(localhost vs 0.0.0.0)
  • Kubernetes Service名の解決失敗

関連エラー

関連エラー

gRPC の他のエラー

最終更新: 2025-12-10