Kubernetes中如何配置Service的DNS名称实现集群内跨服务访问?
Great questions! Let's break this down step by step for your MySQL Kubernetes setup:
1. How to access a Service using its DNS name in a Kubernetes cluster
Kubernetes relies on CoreDNS (or kube-dns in older clusters) to auto-generate DNS records for every Service. The standard DNS format for a Service is:
<service-name>.<namespace>.svc.cluster.local
- Same namespace: If your client Pod/Service lives in the same namespace as the target Service (like your
databaseService), you can use the shorthand<service-name>directly. For your setup, that's justdatabaseto reach the MySQL Service on port 3306. - Cross namespace: If accessing from a different namespace, use the full qualified domain name (FQDN):
database.default.svc.cluster.local(replacedefaultwith your actual namespace if it's not the default one). - Shorter cross-namespace shortcut: You can also use
<service-name>.<namespace>(e.g.,database.default) since the cluster's DNS search domains typically include the local namespace andsvc.cluster.local.
2. How to set a custom DNS name for your Service (and modify your config)
The primary DNS name for your Service is tied to its metadata.name and its namespace. If you want to adjust the DNS name other Services use to reach your MySQL instance, here are two straightforward options:
Option 1: Rename the Service (simplest for a primary custom DNS name)
Just update the metadata.name field in your Service configuration. For example, if you want the DNS name to be mysql-db instead of database, modify the Service section like this:
apiVersion: v1 kind: Service metadata: name: mysql-db # Changed from "database" to your desired DNS name labels: app: db spec: selector: app: db type: ClusterIP ports: - name: database port: 3306 targetPort: 3306
After applying this updated config with kubectl apply -f your-config-file.yaml, other Services in the same namespace can access MySQL using mysql-db, and cross-namespace access uses mysql-db.default.svc.cluster.local.
Option 2: Add a DNS alias (for multiple names pointing to the same Service)
If you want to keep the original database name but add an extra alias (like mysql-service), create an ExternalName Service that points to the original Service's FQDN. Here's an example:
apiVersion: v1 kind: Service metadata: name: mysql-service spec: type: ExternalName externalName: database.default.svc.cluster.local
Now both database and mysql-service will resolve to your MySQL Service.
For your existing MySQL config
Your current Service is named database, so it's already accessible via database (same namespace) or database.default.svc.cluster.local (cross-namespace). If you want a different primary DNS name, just edit the metadata.name field in the Service portion of your config file as shown in Option 1.
内容的提问来源于stack exchange,提问作者sandeep P

