Skip to main content

Services & Ingress

Core

Drill until fluent: hands-on rounds test this directly. Phase 2 of the Learning Path.

Docs: Service Β· EndpointSlices Β· DNS for Services and Pods Β· Ingress Β· Gateway API

Overview​

Pods are replaced all the time and every replacement gets a new IP, so nothing should talk to a Pod IP directly. A Service gives a set of Pods one stable virtual IP and DNS name. It finds its Pods by label selector and nothing else. The EndpointSlice controller keeps the list of Ready, matching Pod IPs current, and kube-proxy on each node routes the virtual IP to them. An Ingress adds HTTP routing on top: one external entry point that sends shop.example.com/api to one Service and / to another. An Ingress does nothing unless an Ingress controller is installed. Almost every "can't reach my app" question is answered by walking this path hop by hop.

Request path: client to Ingress to Service api to EndpointSlice to two Pods labelled app=api in namespace shop, with NetworkPolicy gates at the namespace boundary; a third Pod labelled app=web receives nothingRequest path: client to Ingress to Service api to EndpointSlice to two Pods labelled app=api in namespace shop, with NetworkPolicy gates at the namespace boundary; a third Pod labelled app=web receives nothing

Figure 10-1: The request path. Amber marks labels and the selector that matches them, the only link between a Service and its Pods. Grey is a Pod the selector doesn't match. The dark bars are NetworkPolicy checks (β†’ Network Policy).

Key concepts​

Service types​

TypeReachable fromHowUse when
ClusterIP (default)Inside the clusterVirtual IP + DNS nameService-to-service traffic
NodePortOutside, via <any-node-ip>:30000–32767Opens the port on every nodeQuick tests, or behind your own load balancer
LoadBalancerOutside, via a cloud load balancerNodePort + a provisioned external LBOne externally exposed TCP/UDP service
ExternalNameInsideDNS CNAME to an outside nameAlias an external database
Headless (clusterIP: None)InsideDNS returns Pod IPs directly, no virtual IPStatefulSets, client-side load balancing

The four ports​

FieldWhereMeaning
containerPortPod specWhat the app listens on. Informational only.
targetPortServiceWhere the Service sends traffic on the Pod. Must match what the app listens on.
portServiceWhat clients connect to on the Service IP
nodePortService (NodePort/LB)Port opened on every node
Service port β†’ targetPortApp listens onResult
80 β†’ 80808080Works
80 β†’ 808080Endpoints exist, but connections are refused
80 β†’ http (named)Port named http in the Pod specWorks, and survives the app changing port numbers

DNS names​

NameResolves from
apiSame namespace
api.shopAny namespace
api.shop.svc.cluster.localAnywhere in the cluster (fully qualified)
db-0.db.shop.svc.cluster.localA single StatefulSet Pod behind a headless Service

Ingress vs Gateway API​

Gateway API exists because Ingress only standardised host and path routing. Everything else (traffic weights, header matching, timeouts, TLS details) became controller-specific annotations, so an Ingress written for one controller didn't work on another.

IngressGateway API
APInetworking.k8s.io/v1, stable, in the CKAD curriculumgateway.networking.k8s.io/v1, the successor
ModelOne object: host + path rulesSplit roles: GatewayClass (infra), Gateway (platform), HTTPRoute (app team)
Traffic splitting, header matchingController-specific annotationsBuilt in (weights, headers)
Needs a controllerYesYes

β†’ Why the labs still use ingress-nginx: the retirement note.

kubectl essentials​

Expose and inspect:

kubectl expose deployment api --port=80 --target-port=8080 # ClusterIP
kubectl expose deployment api --port=80 --target-port=8080 --type=NodePort --name=api-np
kubectl create service clusterip api --tcp=80:8080 --dry-run=client -o yaml # selector is app=api
kubectl get svc,endpointslices -l app=api
kubectl get endpointslices -l kubernetes.io/service-name=api -o wide # the actual Pod IPs
kubectl describe svc api # Selector, TargetPort, Endpoints
kubectl get pods -l app=api --show-labels # does the selector match anything?

Test from inside the cluster:

kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://api
kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- nslookup api.shop
kubectl port-forward svc/api 8080:80 # then curl localhost:8080

Ingress:

kubectl create ingress shop --class=nginx \
--rule="shop.example.com/api*=api:80" --rule="shop.example.com/*=web:80"
kubectl get ingressclass
kubectl describe ingress shop # rules and resolved backends

A Service with a named target port:

apiVersion: v1
kind: Service
metadata:
name: api
spec:
type: ClusterIP
selector:
app: api # must match the Pod template labels exactly
ports:
- name: http
port: 80
targetPort: http # the containerPort named "http"

An Ingress routing by path:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop
spec:
ingressClassName: nginx
tls:
- hosts: [shop.example.com]
secretName: shop-tls # a kubernetes.io/tls Secret
rules:
- host: shop.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: api
port: {number: 80}
- path: /
pathType: Prefix
backend:
service:
name: web
port: {number: 80}

πŸ§ͺ Lab​

Lab 2-4 β˜…β˜…

Requires: Standard lab setup Β· Lab 1-1 Β· How the tiers work.

Break the link between a Service and its Pods, then find it. Lab 1-1 does the basic selector break; this lab adds targetPort and Ingress.

Goal

  1. In namespace lab2-4, create Deployment api (registry.k8s.io/e2e-test-images/agnhost:2.53, args netexec --http-port=8080, 2 replicas).
  2. Expose it as Service api on port 80 β†’ 8080. Call it from a temporary Pod.
  3. Patch the Service selector to app: apii. Call it again and find the cause using only kubectl get/describe.
  4. Fix the selector, then change targetPort to 9090 and describe how the symptom differs.
  5. Create an Ingress shop routing /api to api:80 and check its backends with kubectl describe.

Verify

kubectl -n lab2-4 get endpointslices -l kubernetes.io/service-name=api # 2 endpoints after the fix
kubectl -n lab2-4 run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://api/hostname
🟑 Hints
  1. agnhost is in the image kit. Note how -- behaves under create deployment.
  2. kubectl expose -h: look at --port and --target-port.
  3. kubectl describe svc shows Selector and Endpoints. Compare with kubectl get pods --show-labels.
  4. kubectl patch --type=json can replace /spec/ports/0/targetPort. Is the error the same? What does describe svc show this time?
  5. "Route HTTP by host and path" in Command Patterns.
🟒 Guided
  1. Create the lab namespace.

    kubectl create namespace lab2-4
  2. Run 2 agnhost Pods serving HTTP on 8080 (create deployment: the words after -- replace the entrypoint).

    kubectl -n lab2-4 create deployment api --image=registry.k8s.io/e2e-test-images/agnhost:2.53 \
    --replicas=2 --port=8080 -- /agnhost netexec --http-port=8080
  3. Create a Service: port 80 on the Service, 8080 on the Pods.

    kubectl -n lab2-4 expose deployment api --port=80 --target-port=8080
  4. Call it from a throwaway Pod: prints the serving Pod's name.

    kubectl -n lab2-4 run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://api/hostname
  5. Break the selector with a typo.

    kubectl -n lab2-4 patch svc api -p '{"spec":{"selector":{"app":"apii"}}}'
  6. Call it again: Connection refused, although DNS still resolves.

    kubectl -n lab2-4 run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://api/hostname
  7. See why: Endpoints: <none>.

    kubectl -n lab2-4 describe svc api
  8. The Pods are app=api; the selector says app=apii.

    kubectl -n lab2-4 get pods --show-labels
  9. Fix the selector.

    kubectl -n lab2-4 patch svc api -p '{"spec":{"selector":{"app":"api"}}}'
  10. Send traffic to a port nothing listens on.

    kubectl -n lab2-4 patch svc api --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":9090}]'
  11. Call it: also "Connection refused", but now describe svc lists endpoints; the Pod itself refuses.

    kubectl -n lab2-4 run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://api/hostname
  12. Put targetPort back.

    kubectl -n lab2-4 patch svc api --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8080}]'
  13. Route shop.example.com/api to the Service.

    kubectl -n lab2-4 create ingress shop --rule="shop.example.com/api*=api:80"
  14. Check the backends: api:80 (10.244.x.x:8080,...).

    kubectl -n lab2-4 describe ingress shop

    ADDRESS stays empty and nothing routes until an Ingress controller runs. Lab 2-5 installs one and sends real traffic.

  15. Run the βœ… Check below, then delete everything the lab created.

    kubectl delete namespace lab2-4

βœ… Check

t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
kubectl -n lab2-4 run chk --image=busybox:1.36 --restart=Never -- sleep 600 2>/dev/null; kubectl -n lab2-4 wait --for=condition=Ready pod/chk >/dev/null
t "selector fixed" "$(kubectl -n lab2-4 get svc api -o jsonpath='{.spec.selector.app}')" "api"
t "targetPort 8080" "$(kubectl -n lab2-4 get svc api -o jsonpath='{.spec.ports[0].targetPort}')" "8080"
t "2 endpoints" "$(kubectl -n lab2-4 get endpointslices -l kubernetes.io/service-name=api -o jsonpath='{range .items[*].endpoints[*]}x{end}')" "xx"
t "Service answers" "$(kubectl -n lab2-4 exec chk -- wget -qO- -T 3 http://api/hostname | cut -c1-4)" "api-"
t "Ingress routes /api" "$(kubectl -n lab2-4 get ingress shop -o jsonpath='{.spec.rules[0].http.paths[0].backend.service.name}')" "api"
Lab 2-5 β˜…β˜…

Requires: Cluster add-ons (port mappings + ingress-nginx) Β· Lab 2-4 Β· How the tiers work.

Route two Services through one Ingress, from your laptop.

Goal

  1. In namespace lab2-5, create Deployment api (agnhost netexec on 8080, 2 replicas) with Service api on 80 β†’ 8080, and Deployment web (nginx:1.27) with Service web on 80.
  2. Create one Ingress shop, class nginx, host shop.localhost: /api goes to api, everything else to web.
  3. From your laptop, curl /, /api and /apiv1. Which backend answered each, and how can you tell?
  4. Curl a host the Ingress doesn't know. Who answers now?

Verify

curl -s http://shop.localhost/ | grep -o '<title>.*</title>' # <title>Welcome to nginx!</title>
curl -s http://shop.localhost/api # NOW: 2026-... (agnhost)
curl -s -o /dev/null -w '%{http_code}\n' http://other.localhost/ # 404
🟑 Hints
  1. Same commands as Lab 2-4 steps 2–3, twice.
  2. "Route HTTP by host and path" in Command Patterns. --rule can repeat; --class picks the controller.
  3. agnhost answers unknown paths with NOW: <time>. nginx answers with HTML. pathType: Prefix matches whole path segments.
  4. A 404 has a footer. Compare it with the one from /apiv1, and read kubectl logs deploy/web.
🟒 Guided
  1. Create the namespace and both backends.

    kubectl create namespace lab2-5
    kubectl -n lab2-5 create deployment api --image=registry.k8s.io/e2e-test-images/agnhost:2.53 \
    --replicas=2 --port=8080 -- /agnhost netexec --http-port=8080
    kubectl -n lab2-5 expose deployment api --port=80 --target-port=8080
    kubectl -n lab2-5 create deployment web --image=nginx:1.27
    kubectl -n lab2-5 expose deployment web --port=80
  2. Create the Ingress. The more specific path wins, whatever the rule order.

    kubectl -n lab2-5 create ingress shop --class=nginx \
    --rule="shop.localhost/api*=api:80" --rule="shop.localhost/*=web:80"
    kubectl -n lab2-5 describe ingress shop | sed -n '/Rules/,/Annotations/p'
    Rules:
    Host Path Backends
    ---- ---- --------
    shop.localhost
    /api api:80 (10.244.0.172:8080,10.244.0.171:8080)
    / web:80 (10.244.0.173:80)

    The generator's api* becomes path: /api with pathType: Prefix.

  3. Curl each path from your laptop.

    curl -s http://shop.localhost/ | grep -o '<title>.*</title>'
    curl -s http://shop.localhost/api
    curl -s http://shop.localhost/apiv1 | tail -3
    <title>Welcome to nginx!</title>
    NOW: 2026-09-27 09:56:00.194899043 +0000 UTC m=+5.235875961
    <hr><center>nginx/1.27.5</center>
    </body>
    </html>

    /api reached agnhost. /apiv1 is not under the /api prefix, because Prefix matches whole segments, so it went to web, whose nginx has no such file. The versioned footer and kubectl -n lab2-5 logs deploy/web both show the web Pod served that 404.

  4. Curl a host with no rule.

    curl -s http://other.localhost/ | tail -3
    <hr><center>nginx</center>
    </body>
    </html>

    A different 404: no version in the footer. The controller answered itself, because no rule matched the host. No Pod was involved.

  5. Run the βœ… Check below, then delete everything the lab created.

    kubectl delete namespace lab2-5

βœ… Check

t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
t "/ reaches web" "$(curl -s http://shop.localhost/ | grep -o '<title>.*</title>')" "<title>Welcome to nginx!</title>"
t "/api reaches api" "$(curl -s http://shop.localhost/api | cut -c1-4)" "NOW:"
t "/apiv1 goes to web" "$(curl -s http://shop.localhost/apiv1 | grep -o 'nginx/1.27')" "nginx/1.27"
t "unknown host is a 404" "$(curl -s -o /dev/null -w '%{http_code}' http://other.localhost/)" "404"
t "Ingress has 2 backends" "$(kubectl -n lab2-5 get ingress shop -o jsonpath='{.spec.rules[0].http.paths[*].backend.service.name}')" "api web"

Gotchas​

  • Selector typos fail silently. The Service is created and DNS resolves; it just has no endpoints.
  • "Connection refused" has two causes. kube-proxy rejects connections to a Service with no endpoints, and a wrong targetPort is refused by the Pod. describe svc tells them apart: empty vs listed Endpoints. A NetworkPolicy drop times out instead.
  • Not Ready means not an endpoint. A failing readiness probe removes the Pod from the EndpointSlice. β†’ See Probes & Observability.
  • Short names only work in the same namespace. Across namespaces use api.shop.
  • An Ingress with no controller does nothing. ADDRESS stays empty. Check kubectl get ingressclass.
  • pathType is required. Prefix matches path segments (/api matches /api/v1, not /apiv1). Exact matches one path.
  • kubectl get endpoints is deprecated. The Endpoints API is deprecated in favour of EndpointSlices. Use kubectl get endpointslices.

Scenario questions​

Q1 β˜… A Service exists and DNS resolves, but every request gets "connection refused". What do you check?

Model answer
  • Clarify: did it ever work? What changed?
  • Observe: kubectl describe svc β†’ Endpoints: <none>. Compare Selector with kubectl get pods --show-labels.
  • Hypothesise: the selector doesn't match the Pod labels, or matching Pods exist but none are Ready. With no endpoints, kube-proxy rejects the connection, which is why it's refused rather than timing out.
  • Fix: correct the selector or labels, or fix whatever keeps the Pods from becoming Ready.
  • Prevent: generate Service and Deployment from the same template (Helm/Kustomize) so labels can't drift apart. Alert on Services with zero endpoints.

Q2 β˜…β˜… Port-forwarding to a Pod works, but going through the Service fails with "connection refused". Why?

Model answer
  • Clarify: which port does the app listen on, and what does the Service say?
  • Observe: kubectl describe svc shows TargetPort: 80/TCP; the port-forward used 8080. Endpoints are listed.
  • Hypothesise: targetPort points at a port where nothing listens. Endpoints exist, so this refusal comes from the Pod itself, not from kube-proxy.
  • Fix: set targetPort: 8080, or better, name the container port and use targetPort: http.
  • Prevent: named ports keep the Service correct when the app's port changes.

Q3 β˜…β˜… You need to expose five HTTP services externally. LoadBalancer per Service, or Ingress?

Model answer
  • Clarify: all HTTP? Same domain? TLS required? Any non-HTTP protocols?
  • Observe: each LoadBalancer Service provisions a separate cloud load balancer and IP, with its own cost and certificate handling.
  • Hypothesise: HTTP services sharing a domain belong behind one entry point that routes by host and path and terminates TLS once.
  • Fix: one Ingress (or Gateway API HTTPRoutes) in front of five ClusterIP Services. Keep LoadBalancer for non-HTTP protocols such as a TCP game server or MQTT.
  • Prevent: the trade-off: a shared entry point is a shared failure domain and needs capacity planning. For a new platform, I'd pick Gateway API: standard weights and header matching, and clean role separation.

Q4 β˜…β˜…β˜… Users see a burst of 502s during every rolling deploy, although readiness probes pass. Why?

Model answer
  • Clarify: 502s at startup or at shutdown of Pods? Through the Ingress, or also Service-to-Service?
  • Observe: errors line up with old Pods terminating. The proxy logs show connections reset by upstream.
  • Hypothesise: on deletion, the kubelet sends SIGTERM while endpoint removal is still propagating to kube-proxy and the Ingress controller. For a moment, traffic still arrives at a Pod that has stopped accepting it.
  • Fix: a preStop hook that sleeps 5–10 s, so the Pod keeps serving until everyone has removed it, plus graceful shutdown in the app and a terminationGracePeriodSeconds longer than both (β†’ termination sequence).
  • Prevent: add connection draining to the release checklist and test it with load running during a deploy. β†’ See Zero-Downtime Release.

Summary​

  • Services find Pods by label only. Check describe svc β†’ Endpoints before anything else.
  • port is the Service's, targetPort is the app's. Name ports to avoid mismatches.
  • Only Ready Pods receive traffic. Readiness probes control Service membership.
  • Use DNS names, not IPs. svc.namespace works across namespaces.
  • Ingress routes HTTP and needs a controller. Gateway API is its successor; both are worth knowing.

Next in path β†’ Container Images