When an application (Application A) in Kubernetes relies on a Service name to connect to another application (Application B), and the pods backing that Service become unavailable without a quick recovery, connectivity fails. To restore service without altering Application A's connection method, you can redirect traffic to an external application (Application C) outside the cluster by modifying the Service's endpoints.
1. Backup Original Service and Endpoint Configurations
First, export the current Service and Endpoint resources as YAML files for backup.
kubectl -n default get svc backend-svc -o yaml > backend-svc-original.yaml
kubectl -n default get ep backend-svc -o yaml > backend-svc-endpoints-original.yaml
cp backend-svc-original.yaml backend-svc-modified.yaml
cp backend-svc-endpoints-original.yaml backend-svc-endpoints-modified.yaml
2. Remove and Replace the Original Seervice
Delete the existing Service to detach it from the faulty pods, then update the backup YAML to reference the external application.
kubectl -n default delete svc backend-svc
vim backend-svc-modified.yaml
Apply the modified Service configuration.
kubectl -n default apply -f backend-svc-modified.yaml
3. Create a New Service with the Original Name
Construct a new Service using the same name that Application A expects, but configure it to point to the external application via endpoints.
apiVersion: v1
kind: Service
metadata:
name: backend-svc
namespace: default
spec:
clusterIP: None
ports:
- name: web
port: 80
protocol: TCP
targetPort: 80
---
apiVersion: v1
kind: Endpoints
metadata:
name: backend-svc
namespace: default
subsets:
- addresses:
- ip: 192.168.1.251
ports:
- name: web
port: 3389
protocol: TCP
Apply the new configuration.
kubectl apply -f backend-svc-new.yaml
After execution, verify the Service and Endpoints reflect the external IP.
kubectl get svc,ep
Output example:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3h12m
service/backend-svc ClusterIP None <none> 80/TCP 76m
NAME ENDPOINTS AGE
endpoints/kubernetes 172.17.0.2:6443 3h12m
endpoints/backend-svc 192.168.1.251:3389 74m
Application A can now reach the external application at 192.168.1.251:3389 using the unchanged Service name backend-svc.