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.
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
dbContainername only has meaning within the same Pod (if you’ve packed multiple containers into one Pod), but even then you’d uselocalhostsince 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.
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
selectorin your Service matches the labels on your database Pod. Runkubectl 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

