如何通过Deployment类型Pod访问Elasticsearch StatefulSet
Hey there! Let's walk through how to get your Redis pod communicating with your Elasticsearch cluster. First, let's break down the key context: your Elasticsearch StatefulSet and its Headless Service live in the elasticsearch-namespace namespace, while your Redis Deployment is (I assume) in the default namespace since it doesn't specify one. Kubernetes has straightforward ways for cross-namespace pod communication, so let's cover your options.
Option 1: Use the Existing Headless Service (Recommended)
You already have a Headless Service named elasticsearch for your ES StatefulSet—this is perfect for pod-to-pod communication within the cluster. Kubernetes assigns a fully qualified domain name (FQDN) to every service, which you can use from any namespace.
From your Redis pod, you can access Elasticsearch's REST API using this FQDN:
elasticsearch.elasticsearch-namespace.svc.cluster.local:9200
Why this is the best choice? Headless Services resolve directly to the individual IPs of your ES StatefulSet pods, which is ideal for Elasticsearch clients that benefit from node discovery. No extra service setup needed!
Option 2: Fix Your elasticsearch-tcp Service for Load-Balanced Access
If you prefer a load-balanced entry point to your ES cluster (instead of targeting individual nodes), you can tweak your existing elasticsearch-tcp Service. It's almost right—you just need to make sure it's configured for cluster-internal access (which it is by default, but let's make it explicit):
kind: Service apiVersion: v1 metadata: name: elasticsearch-tcp namespace: elasticsearch-namespace labels: app: elasticsearch spec: type: ClusterIP # This is the default, but adding it makes the intent clear selector: app: elasticsearch ports: - protocol: TCP port: 9200 targetPort: 9200
Once this Service is applied, your Redis pod can access it using its FQDN too:
elasticsearch-tcp.elasticsearch-namespace.svc.cluster.local:9200
Quick Checks to Ensure Everything Works
- Namespace Confirmation: If your Redis Deployment is actually in the
elasticsearch-namespace(not default), you can skip the full FQDN and just useelasticsearch:9200orelasticsearch-tcp:9200directly. - Network Policies: If your cluster uses NetworkPolicies, double-check that traffic from your Redis pod's namespace is allowed to reach port 9200 on Elasticsearch pods in
elasticsearch-namespace. - Test Connectivity: You can verify access by exec'ing into your Redis pod and running a curl command:
If you get Elasticsearch's cluster metadata response, you're good to go!kubectl exec -it $(kubectl get pods -l app=redis-ws-app -o jsonpath='{.items[0].metadata.name}') -- sh curl elasticsearch.elasticsearch-namespace.svc.cluster.local:9200
内容的提问来源于stack exchange,提问作者Artur Drożdżyk

