When we create a service in K8S, a Endpoint object is also created with the same name as the service. Service knows how to send traffic to corresponding Pods. This is done by a mapping within the Endpoint object.
Lets take a look at some examples
A wordpress service
kubectl get svc -n wordpress-ns
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
wordpress LoadBalancer 10.100.200.174 100.64.144.7,192.168.160.115 80:31895/TCP 3d23h
wordpress pods
kubectl get pods -n wordpress-ns -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
wordpress-dccb8668f-5dfjc 1/1 Running 0 24m 40.0.4.3 244dee94-bfa7-4413-9135-34f902040d7e <none> <none>
wordpress-dccb8668f-ntbm8 1/1 Running 0 3d23h 40.0.4.4 9aeea30f-f08b-47b3-b7aa-ef45f3e800b0 <none> <none>
wordpress endpoints
kubectl get endpoints -n wordpress-ns
NAME ENDPOINTS AGE
wordpress 40.0.4.3:80,40.0.4.4:80 3d23h
As we can see, the Endpoints object as the mapping with corresponding Pod IPs which let the service could know where to send the traffics to.
We could also edit the Endpoints object to let the service sends traffics to some external services outside of the cluster. See this post for more details.