Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

Kubernetes Services: expose and connect your applications

By updated

Improve this page

Logo Kubernetes

A Service gives a group of Pods an IP address that does not change and a DNS name. Pods disappear and come back with another address: callers therefore talk to the Service, which spreads their requests between the healthy Pods. In this lesson, you expose three Pods that each answer with their own name, you prove from a client Pod that all three receive traffic, you break then repair the selector, you reach the Service by its name from another namespace, and you switch traffic from one version to the other.

Prerequisites: the demo cluster from First cluster (created with the kind-multi file) and the lesson Deployments. All commands are typed in the default namespace, unless stated otherwise.

What you will learn

  • Create a Service with kubectl expose and read its YAML equivalent
  • Tell port from targetPort when the application does not listen on the port of the Service
  • Read the endpoints of a Service and diagnose a Service that has none
  • Prove the traffic spreading between several Pods from a client Pod
  • Reach a Service by its DNS name, in the same namespace and from another one
  • Choose between ClusterIP, NodePort, LoadBalancer and Headless
  • Switch traffic between two Deployments by changing the selector

Why is a Pod not enough as an access point?

Each Pod receives its own IP address, but this address is not a service address: it changes when the Pod is recreated, for example after an update or the failure of a node. A caller that noted the address of a Pod would therefore lose its target at each replacement.

The Service solves this problem in two ways. It keeps an address (the ClusterIP) and a DNS name for its whole life, and it keeps up to date the list of Pods that can answer. This list is called the endpoints: the Service computes it by looking for the Pods whose labels match its selector, and only the ready Pods (complete READY column) receive traffic.

Inside the cluster, a Frontend Pod calls backend-service, a Service of type ClusterIP, which relays the traffic to the Backend Pods without ever leaving the cluster.ClusterFrontend Podbackend-serviceService ClusterIPBackend Pods
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The diagram shows a caller that only knows the name of the Service: the Service picks one Pod among those that match its selector. The rest of the lesson checks each arrow with a command.

How do you expose three Pods through a Service?

The starting point is a Deployment of three replicas where each Pod answers with its own name. The busybox image is enough: its httpd HTTP server listens on port 8080 and serves a page that contains the name of the Pod, written at startup. Port 8080 matters for what follows, because the Service will listen on another port.

Terminal window
kubectl apply -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: reponse
spec:
replicas: 3
selector:
matchLabels:
app: reponse
template:
metadata:
labels:
app: reponse
spec:
containers:
- name: reponse
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command: ["sh", "-c"]
args:
- mkdir -p /www && echo "Je suis $(hostname)" > /www/index.html && httpd -f -p 8080 -h /www
ports:
- containerPort: 8080
EOF
kubectl rollout status deployment/reponse
kubectl get pods -l app=reponse -o wide
deployment.apps/reponse created
Waiting for deployment "reponse" rollout to finish: 0 out of 3 new replicas have been updated...
Waiting for deployment "reponse" rollout to finish: 0 of 3 updated replicas are available...
Waiting for deployment "reponse" rollout to finish: 1 of 3 updated replicas are available...
Waiting for deployment "reponse" rollout to finish: 2 of 3 updated replicas are available...
deployment "reponse" successfully rolled out
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
reponse-f5d59fc45-2dsbn 1/1 Running 0 3s 10.244.2.2 demo-worker2 <none> <none>
reponse-f5d59fc45-nxfvg 1/1 Running 0 3s 10.244.1.2 demo-worker <none> <none>
reponse-f5d59fc45-szvtl 1/1 Running 0 3s 10.244.4.2 demo-worker3 <none> <none>

Note the three IP addresses of the IP column (here 10.244.2.2, 10.244.1.2 and 10.244.4.2, yours will be different): they are used further down to compare with the endpoints of the Service. The names of the Pods carry a random suffix, which changes at each creation.

Now create the Service. The kubectl expose command reads the selector of the Deployment and reuses it for the Service. Here, the Service listens on port 80 (--port) and sends traffic to port 8080 of the Pods (--target-port):

Terminal window
kubectl expose deployment reponse --name=reponse --port=80 --target-port=8080
kubectl get svc reponse -o wide
service/reponse exposed
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
reponse ClusterIP 10.96.7.43 <none> 80/TCP 0s app=reponse

The SELECTOR column says which labels the Service looks for, and PORT(S) recalls that it listens on 80/TCP. The next command prints the equivalent YAML manifest, without creating anything, to see where the selector, port and targetPort fields sit:

Terminal window
kubectl expose deployment reponse --name=reponse --port=80 --target-port=8080 --dry-run=client -o yaml
apiVersion: v1
kind: Service
metadata:
name: reponse
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8080
selector:
app: reponse
status:
loadBalancer: {}
FieldRole
selectorThe labels of the Pods to target: every Pod that carries them becomes an endpoint
portThe port the Service listens on, the one the caller uses
targetPortThe port the container actually listens on
typeThe exposure mode, ClusterIP when absent

The Service listens on 80 and the application on 8080, and this is exactly why targetPort exists: without it, the Service would send requests to port 80 of the Pods, where nobody listens.

How do you see the Pods behind a Service?

A Service that exists is not necessarily a Service that is useful. The check is done in the endpoints, which Kubernetes stores in an EndpointSlice object:

Terminal window
kubectl get endpointslice -l kubernetes.io/service-name=reponse
kubectl describe svc reponse
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
reponse-fzsrv IPv4 8080 10.244.2.2,10.244.1.2,10.244.4.2 0s
Name: reponse
Namespace: default
Labels: <none>
Annotations: <none>
Selector: app=reponse
Type: ClusterIP
IP Family Policy: SingleStack
IP Families: IPv4
IP: 10.96.7.43
IPs: 10.96.7.43
Port: <unset> 80/TCP
TargetPort: 8080/TCP
Endpoints: 10.244.2.2:8080,10.244.1.2:8080,10.244.4.2:8080
Session Affinity: None
Internal Traffic Policy: Cluster
Events: <none>

Compare the ENDPOINTS column with the addresses noted above: they are the same, on port 8080 (the order may differ). The random suffix of the EndpointSlice name will be different on your side. In describe, the Endpoints line does the same job; if it is empty, the Service sends traffic to nobody.

You will see in old tutorials the kubectl get endpoints command: it still works, but prints a deprecation warning (v1 Endpoints is deprecated in v1.33+). Get into the habit of querying endpointslice.

How do you prove that the Service spreads requests?

To call a ClusterIP Service, you have to be inside the cluster. Start a client Pod that stays alive, wait until it is ready, then send twelve requests to the name of the Service:

Terminal window
kubectl run client --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --restart=Never -- sleep 3600
kubectl wait --for=condition=Ready pod/client --timeout=60s
for i in $(seq 1 12); do kubectl exec client -- wget -qO- http://reponse; done | sort | uniq -c
pod/client created
pod/client condition met
3 Je suis reponse-f5d59fc45-2dsbn
7 Je suis reponse-f5d59fc45-nxfvg
2 Je suis reponse-f5d59fc45-szvtl

Look at how many different lines are displayed: each line is a Pod that answered, and the number in front of it says how many requests it received. Here, the three Pods answer, with 3, 7 and 2 requests out of 12.

The Service picks a Pod at random for each connection, so the counters are not equal (on your side, they will be different). What matters is that the traffic does not go to a single Pod. The client used only one name, reponse, and never the address of a Pod.

What happens when the selector finds no Pod?

This is a classic mistake: the selector of the Service matches no Pod label, for example after a typo. Kubernetes accepts this Service without any error. Trigger it on purpose by changing the selector to a value that no Pod carries:

Terminal window
kubectl patch svc reponse -p '{"spec":{"selector":{"app":"reponses"}}}'
kubectl get endpointslice -l kubernetes.io/service-name=reponse
kubectl exec client -- wget -qO- -T 3 http://reponse
service/reponse patched
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
reponse-fzsrv IPv4 <unset> <unset> 3s
wget: can't connect to remote host (10.96.7.43): Connection refused
command terminated with exit code 1

The last command fails with Connection refused, and this is the expected result. The Service exists, its name resolves to its ClusterIP, but the ENDPOINTS column of the EndpointSlice shows <unset>: nobody receives the connection. The failure is only visible in the endpoints, never in the creation of the Service. Compare the labels of the Pods with the selector to find the gap, then restore the right selector:

Terminal window
kubectl get pods --show-labels
kubectl get svc reponse -o jsonpath='{.spec.selector}'
kubectl patch svc reponse -p '{"spec":{"selector":{"app":"reponse"}}}'
kubectl get endpointslice -l kubernetes.io/service-name=reponse
kubectl exec client -- wget -qO- http://reponse
NAME READY STATUS RESTARTS AGE LABELS
client 1/1 Running 0 4s run=client,topology.kubernetes.io/zone=zone-a
reponse-f5d59fc45-2dsbn 1/1 Running 0 7s app=reponse,pod-template-hash=f5d59fc45,topology.kubernetes.io/zone=zone-b
reponse-f5d59fc45-nxfvg 1/1 Running 0 7s app=reponse,pod-template-hash=f5d59fc45,topology.kubernetes.io/zone=zone-a
reponse-f5d59fc45-szvtl 1/1 Running 0 7s app=reponse,pod-template-hash=f5d59fc45,topology.kubernetes.io/zone=zone-c
{"app":"reponses"}service/reponse patched
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
reponse-fzsrv IPv4 8080 10.244.1.2,10.244.2.2,10.244.4.2 4s
Je suis reponse-f5d59fc45-2dsbn

The JSONPath of kubectl get svc does not add a line break: the output {"app":"reponses"} sticks to the next line. It confirms the gap, because the Pods carry app=reponse and the selector says reponses. After the repair, the three endpoints come back and the client receives an answer.

A selector with no match is not the only cause of traffic that does not arrive: Pods that are selected but not ready receive no traffic. The EndpointSlice keeps them with the condition ready: false, and the ENDPOINTS column of kubectl get endpointslice shows their address. The Endpoints line of kubectl describe service, for its part, lists only the ready endpoints.

This case belongs to the readiness probes, described in the lesson Probes. For a complete diagnostic method, see Debug a Kubernetes application.

How do you reach a Service by its DNS name?

Each Service receives a DNS name that CoreDNS resolves, in the form <service>.<namespace>.svc.cluster.local. From a Pod of the same namespace, the short name reponse is enough. From another namespace, you have to add the namespace: reponse.default. Check it with a second namespace and a second client Pod:

Terminal window
kubectl create namespace essai
kubectl run client-essai -n essai --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --restart=Never -- sleep 3600
kubectl wait -n essai --for=condition=Ready pod/client-essai --timeout=60s
kubectl exec -n essai client-essai -- wget -qO- -T 3 http://reponse
kubectl exec -n essai client-essai -- wget -qO- http://reponse.default
namespace/essai created
pod/client-essai created
pod/client-essai condition met
wget: bad address 'reponse'
command terminated with exit code 1
Je suis reponse-f5d59fc45-nxfvg

The first request fails with bad address 'reponse': in the essai namespace, the short name reponse looks for a Service that does not exist in this namespace. The second succeeds because .default designates the right namespace. Namespaces are detailed in the lesson Namespaces.

Also look at how the resolution is done. The client Pod sends its questions to the DNS service of the cluster, whose address is in /etc/resolv.conf:

Terminal window
kubectl exec client -- cat /etc/resolv.conf
kubectl exec client -- nslookup reponse
search default.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5
Server: 10.96.0.10
Address: 10.96.0.10:53
** server can't find reponse.cluster.local: NXDOMAIN
Name: reponse.default.svc.cluster.local
Address: 10.96.7.43
** server can't find reponse.cluster.local: NXDOMAIN
** server can't find reponse.svc.cluster.local: NXDOMAIN
** server can't find reponse.svc.cluster.local: NXDOMAIN
command terminated with exit code 1

The search line explains why the short name works: the resolver tries reponse.default.svc.cluster.local by completing the name with each search domain.

nslookup shows here a correct answer (reponse.default.svc.cluster.local returns the ClusterIP of the Service), then several NXDOMAIN lines and exit code 1. These lines do not signal a DNS failure: the busybox nslookup also tries the other search domains (reponse.svc.cluster.local, reponse.cluster.local), which do not exist, and reports a global failure while the name of the Service is resolved.

To test that an application reaches a Service, prefer wget or curl over nslookup: they are the tools your application uses. Always write the name of the Service, never its ClusterIP, which changes if you recreate the Service. How CoreDNS works is covered in the lesson CoreDNS.

Which Service type should you choose?

To choose, ask yourself who must reach this Service. A caller located in the cluster only needs a ClusterIP, the default type. The three other types serve to leave the cluster or to change the way DNS answers. Create the three types on the same Deployment to compare their TYPE column:

Terminal window
kubectl expose deployment reponse --name=reponse-nodeport --type=NodePort --port=80 --target-port=8080
kubectl expose deployment reponse --name=reponse-lb --type=LoadBalancer --port=80 --target-port=8080
kubectl expose deployment reponse --name=reponse-headless --cluster-ip=None --port=80 --target-port=8080
kubectl get svc
service/reponse-nodeport exposed
service/reponse-lb exposed
service/reponse-headless exposed
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 36s
reponse ClusterIP 10.96.7.43 <none> 80/TCP 9s
reponse-headless ClusterIP None <none> 80/TCP 0s
reponse-lb LoadBalancer 10.96.159.10 <pending> 80:30851/TCP 0s
reponse-nodeport NodePort 10.96.11.119 <none> 80:31662/TCP 0s
TypeWho can call itUse
ClusterIP (default)The Pods of the clusterAn internal API, a database, a cache
NodePortAny client that reaches a node, on a port in the 30000-32767 rangeA local test, a cluster without a cloud
LoadBalancerAny client, through the address provided by the cloud providerAn application exposed on a cloud
Headless (clusterIP: None)The Pods of the cluster, which receive the IPs of the PodsApplications that choose their own Pod
A call coming from the Internet or the external network reaches port 30080 opened on each node, Node 1 as well as Node 2; both nodes send the traffic back to the same ClusterIP Service, which distributes it to the Pods.:30080:30080Internet / external networkNode 1:30080Node 2:30080Service (ClusterIP)Pods
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The diagram shows that a NodePort opens the same port on each node and sends traffic back to the same ClusterIP Service. On kind, as on a bare kubeadm cluster, the reponse-lb Service keeps <pending> in EXTERNAL-IP: no cloud provider supplies an address, and this is not a failure. You would have to add a component that plays this role, like MetalLB or cloud-provider-kind.

A headless Service has no ClusterIP: DNS directly returns the addresses of the Pods. Check it by comparing with the addresses of the Pods:

Terminal window
kubectl exec client -- nslookup reponse-headless
kubectl get pods -l app=reponse -o wide
Server: 10.96.0.10
Address: 10.96.0.10:53
Name: reponse-headless.default.svc.cluster.local
Address: 10.244.1.2
Name: reponse-headless.default.svc.cluster.local
Address: 10.244.2.2
Name: reponse-headless.default.svc.cluster.local
Address: 10.244.4.2
** server can't find reponse-headless.cluster.local: NXDOMAIN
** server can't find reponse-headless.cluster.local: NXDOMAIN
** server can't find reponse-headless.svc.cluster.local: NXDOMAIN
** server can't find reponse-headless.svc.cluster.local: NXDOMAIN
command terminated with exit code 1
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
reponse-f5d59fc45-2dsbn 1/1 Running 0 12s 10.244.2.2 demo-worker2 <none> <none>
reponse-f5d59fc45-nxfvg 1/1 Running 0 12s 10.244.1.2 demo-worker <none> <none>
reponse-f5d59fc45-szvtl 1/1 Running 0 12s 10.244.4.2 demo-worker3 <none> <none>

The three Address lines are those of the three Pods, and no ClusterIP appears. The NXDOMAIN lines that follow are the attempts on the other search domains, as above. This mode serves applications that must reach a specific Pod, like databases managed by a StatefulSet.

How do you switch traffic from one version to the other?

Changing the selector of a Service redirects all the traffic at once to other Pods: this is the principle of blue-green. Two Deployments run side by side, the current version ("blue") and the new one ("green"). Only one is behind the Service, and the switch consists in changing this selector.

Before the patch, the Service site has the selector app=bleu and sends traffic to the blue Pods, while the green Pods run without traffic. After the patch, its selector is app=vert: traffic goes to the green Pods and the blue Pods stay in place, without traffic.Before the patchService siteselector app=bleuBlue PodsGreen Podsno trafficAfter the patchService siteselector app=vertGreen PodsBlue Podsno traffic
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The diagram shows that only the selector of the Service changes: both Deployments stay in place. The notion of deployment strategy, with its variants, is described in deployment strategies; here, you only do the switch and you prove it with the endpoints.

Create the two Deployments. Each one answers with the name of its color, then expose the blue one:

Terminal window
kubectl create deployment bleu --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --replicas=2 --port=8080 -- sh -c 'mkdir -p /www && echo "bleu $(hostname)" > /www/index.html && httpd -f -p 8080 -h /www'
kubectl create deployment vert --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --replicas=2 --port=8080 -- sh -c 'mkdir -p /www && echo "vert $(hostname)" > /www/index.html && httpd -f -p 8080 -h /www'
kubectl rollout status deployment/bleu
kubectl rollout status deployment/vert
kubectl expose deployment bleu --name=site --port=80 --target-port=8080
kubectl get pods -l 'app in (bleu,vert)' -o wide
kubectl get endpointslice -l kubernetes.io/service-name=site
deployment.apps/bleu created
deployment.apps/vert created
Waiting for deployment "bleu" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "bleu" rollout to finish: 1 of 2 updated replicas are available...
deployment "bleu" successfully rolled out
Waiting for deployment "vert" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "vert" rollout to finish: 1 of 2 updated replicas are available...
deployment "vert" successfully rolled out
service/site exposed
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
bleu-569bcfc589-8vhss 1/1 Running 0 1s 10.244.4.4 demo-worker3 <none> <none>
bleu-569bcfc589-fg8zx 1/1 Running 0 1s 10.244.2.3 demo-worker2 <none> <none>
vert-f8d5c5fc7-glnsd 1/1 Running 0 1s 10.244.1.4 demo-worker <none> <none>
vert-f8d5c5fc7-hwv5t 1/1 Running 0 0s 10.244.2.4 demo-worker2 <none> <none>
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
site-bqzrc IPv4 8080 10.244.2.3,10.244.4.4 0s

The endpoints of the site Service are the addresses of the two blue Pods. Query it from the client Pod, switch the selector to vert, then start again:

Terminal window
for i in $(seq 1 6); do kubectl exec client -- wget -qO- http://site; done | sort | uniq -c
kubectl patch svc site -p '{"spec":{"selector":{"app":"vert"}}}'
kubectl get endpointslice -l kubernetes.io/service-name=site
for i in $(seq 1 6); do kubectl exec client -- wget -qO- http://site; done | sort | uniq -c
wget: can't connect to remote host (10.96.51.226): Connection timed out
command terminated with exit code 1
3 bleu bleu-569bcfc589-8vhss
2 bleu bleu-569bcfc589-fg8zx
service/site patched
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
site-bqzrc IPv4 8080 10.244.1.4,10.244.2.4 2m15s
2 vert vert-f8d5c5fc7-glnsd
4 vert vert-f8d5c5fc7-hwv5t

Before the patch, only "blue" answers arrive; after, only "green" ones. In this run, one of the six requests failed on a timeout (Connection timed out), hence only five answers out of six. This isolated failure does not come from the switch, which has not happened yet; if it happens to you, run the loop again. The endpoints changed at the same time as the selector, without touching the Deployments. To go back, you just put app: bleu back: the blue Deployment stayed in place.

What are the limits of a Service?

A Service works on the TCP and UDP layers: it does not read HTTP requests. Routing by path or by host name and TLS termination are the job of an Ingress. A Service does not filter anything either: any Pod of the cluster can call any Service, in any namespace. Access rules are described with NetworkPolicies.

Clean up what you created before moving on:

Terminal window
kubectl delete svc reponse reponse-nodeport reponse-lb reponse-headless site
kubectl delete deployment reponse bleu vert
kubectl delete pod client
kubectl delete namespace essai
service "reponse" deleted from default namespace
service "reponse-nodeport" deleted from default namespace
service "reponse-lb" deleted from default namespace
service "reponse-headless" deleted from default namespace
service "site" deleted from default namespace
deployment.apps "reponse" deleted from default namespace
deployment.apps "bleu" deleted from default namespace
deployment.apps "vert" deleted from default namespace
pod "client" deleted from default namespace
namespace "essai" deleted

Put it into practice

Three labs replay the lesson. The first, expose a Deployment through a ClusterIP Service, asks you to expose busybox Pods that listen on 8080 through a Service on port 80, and the validation checks that several Pods really answer from a client Pod. The second, blue-green, asks you to switch traffic between two Deployments by changing the selector, and the validation reads the endpoints of the Service before and after the switch. The third, repair a NodePort Service, starts from a Service that serves nothing: you find out why and repair it. The validation checks the requested port, the endpoints on the right Pods and a real request to the NodePort from each node.

Key takeaways

  1. A Service gives a group of Pods a stable address and a DNS name.
  2. The selector chooses the Pods; a selector with no match gives a Service without endpoints, and no error.
  3. port is the port of the Service, targetPort that of the container: they can differ.
  4. The endpoints are read with kubectl get endpointslice -l kubernetes.io/service-name=<service>.
  5. From another namespace, you need the name <service>.<namespace>.
  6. ClusterIP serves internal use; NodePort opens a port on each node; LoadBalancer asks the cloud provider for an address (<pending> on kind); Headless returns the addresses of the Pods.
  7. Changing the selector of a Service switches the traffic from one Deployment to the other.
  8. A Service does no HTTP routing, no TLS and no filtering: these are the roles of the Ingress and of NetworkPolicies.

Test your knowledge

Seven questions to check that the essentials are in place: choice of type, role of the selector, reading EndpointSlices and diagnosing a Service that does not answer.

Knowledge check

Check what you have learned with this interactive quiz

7 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

FAQ: frequently asked questions about Services

These questions come up often when you connect applications in Kubernetes. The answers below take up the key points of the guide, Service types, the choice between ClusterIP, NodePort and LoadBalancer, and the diagnosis of missing endpoints.