You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes中Java程序通过容器名连接数据库报UnknownHostException问题排查

Hey there! Let’s break down why you’re getting that UnknownHostException when trying to use your database container name in Kubernetes, and how to fix it.

Why the container name isn’t working

Unlike Docker Compose where container names can be used for inter-container communication, Kubernetes doesn’t resolve container names for service discovery. Here’s the breakdown:

  • The dbContainer name only has meaning within the same Pod (if you’ve packed multiple containers into one Pod), but even then you’d use localhost since they share a network namespace.
  • For communication between separate Pods (which is the standard setup in K8s), you need to use Kubernetes Services—they provide stable DNS names that other Pods can resolve.
Step-by-step fixes to get your connection working

1. Create a Service for your database Pod

First, you need to expose your database Pod with a Service. This creates a persistent DNS entry that your app can rely on.

Save this as db-service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: db-service
spec:
  selector:
    app: db  # This must match the labels on your database Pod
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306
  type: ClusterIP  # Default type, only accessible inside the cluster

Apply it with this command:

kubectl apply -f db-service.yaml

2. Update your JDBC URL to use the Service name

Replace the container name in your connection string with the Service name (db-service in the example above). If your app and database are in the same Kubernetes namespace, you can just use the short name:

public static String url = "jdbc:mysql://db-service:3306/schema1?useSSL=false";

If they’re in different namespaces, use the full DNS name:

public static String url = "jdbc:mysql://db-service.<db-namespace>.svc.cluster.local:3306/schema1?useSSL=false";

3. Verify labels and namespaces

  • Double-check that the selector in your Service matches the labels on your database Pod. Run kubectl describe pods <your-db-pod-name> to see the Pod’s labels.
  • Confirm both your app Pod and database Pod are in the same namespace (or adjust the DNS name as noted above if not).

Bonus: If app and database are in the same Pod

If you’ve deployed both containers in a single Pod (sidecar pattern), you can skip the Service entirely and just use localhost in your JDBC URL—they share the same network stack, so local connections work just like they did on your machine.

内容的提问来源于stack exchange,提问作者Cristian Monti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:31:00