# Services and Network Connectivity

> Chapter 5 of the Courseiva CNCF-KCNA curriculum — https://courseiva.com/learn/cncf-kcna/services-and-networking

**Official objective:** 2.4 — Describe Services, Ingress, and basic network policies.

## Introduction

If you cannot reliably connect users to your application, your app might as well be invisible. That is the problem that Kubernetes network connectivity solves: how to make sure that the right traffic reaches the right container, every time, even when containers are constantly being created, moved, or destroyed. For the KCNA exam, understanding Services, Ingress, and Network Policies is non-negotiable — these are the core tools that control communication within a cluster and between the outside world and your workloads.

## The Apartment Block Mail Room Analogy

Apartment block with twenty flats and a mail room on the ground floor.

Each flat has a unique number, but the postman never remembers which flat is which. He just dumps everything in the mail room. A resident from flat 5 comes down and finds a letter meant for flat 10 — wrong flat, wrong person. The mail room is chaos because there is no system to sort and deliver mail to the right unit.

In this analogy, the apartment block is a Kubernetes cluster (a group of machines running applications). The flats are the individual containers (small packages running your app). The postman is internet traffic arriving from outside. The mail room is a Kubernetes Service — a stable address that sorts incoming traffic and directs it to the correct container. Without a Service, traffic hits random containers or misses them entirely.

Now add a concierge who reads the package label and hands it to the right flat number. That concierge is an Ingress — a smarter entry point that examines the request (like checking if the package is for "billing department" or "support desk") and routes it to the correct set of flats.

Finally, the building manager has rules about who can deliver packages: only residents can receive food deliveries, only staff can access the basement. That manager is a Network Policy — a rulebook limiting which pods (containers) can talk to each other. The mail room, the concierge, and the manager together create a secure, organised delivery system. That is exactly what Services, Ingress, and Network Policies do inside a Kubernetes cluster.

## Core explanation

Let us start with the big picture. A Kubernetes cluster is a group of machines (physical or virtual) that work together to run your applications. Inside the cluster, your applications run in containers, which are lightweight, portable environments that hold everything an app needs to run: code, runtime, system tools, libraries, and settings. Containers are grouped into pods, the smallest deployable unit in Kubernetes. A pod usually runs one container, though it can run several tightly coupled containers.

The problem is that pods are ephemeral (temporary). They can be created, destroyed, or rescheduled onto different machines at any moment. If your database pod crashes and a new pod starts on a different machine, its IP address changes. You cannot hard-code IP addresses — they will break instantly. You need a stable, permanent address that clients can use to reach your application, regardless of which pod is actually running at that moment.

That stable address is a Service. A Service is a Kubernetes resource that provides a single, unchanging endpoint (a combination of IP address and port) for a set of pods. The Service uses selectors (labels) to decide which pods it should route traffic to. For example, you might label all your front-end web server pods with "app: web-frontend". The Service then says: "any pod with the label app: web-frontend is a valid destination for traffic."

There are several types of Services, and the KCNA exam expects you to know their differences:

- ClusterIP: the default type. Exposes the Service on an internal cluster IP. Only reachable from inside the cluster. Used for internal communication between microservices.
- NodePort: exposes the Service on a static port (30000–32767) on every node's IP address. This makes the Service reachable from outside the cluster, though it is not production-grade.
- LoadBalancer: integrates with a cloud provider's load balancer (for example, AWS ELB, Azure Load Balancer, GCP LB). Provides a single external IP address that distributes traffic across the pods. This is the typical way to expose a web app to the internet.
- ExternalName: returns a DNS name instead of a set of pods. This is used to point to an external service, like a legacy database that lives outside the cluster.

An Ingress is a different resource. While a Service operates at Layer 4 (TCP/UDP) — meaning it only handles IP addresses and ports — an Ingress operates at Layer 7 (HTTP/HTTPS). This means it can understand HTTP requests, path-based routing (e.g., /api goes to one Service, /web goes to another), host-based routing (e.g., api.example.com vs www.example.com), and TLS/SSL termination (decrypting HTTPS traffic). Ingress is not a replacement for Services; it sits in front of them. Traffic hits the Ingress, which then forwards it to the appropriate Service based on the URL, hostname, or other rules.

Now for security. By default, all pods in a Kubernetes cluster can communicate with each other. That is a security risk. You might want to restrict traffic — for example, only let the front-end pods talk to the back-end pods, and only let the back-end pods talk to the database pods. That is where Network Policies come in. A Network Policy is a rule that defines how groups of pods are allowed to communicate with each other and with other network endpoints. It works with labels and selectors — you specify which pods the policy applies to (podSelector), and then you define ingress rules (incoming traffic) and egress rules (outgoing traffic). Network Policies are implemented by the cluster's network plugin (such as Calico, Cilium, or Weave Net). If your network plugin does not support Network Policies, the policy will have no effect.

Network Policies are namespace-scoped, meaning they apply to pods within a single namespace. A namespace is a virtual cluster inside a physical cluster, used to organise resources. You might have separate namespaces for development, staging, and production. Network Policies can allow or deny traffic between namespaces too, using namespace selectors in addition to pod selectors.

In short, Services provide stable connectivity to pods, Ingress provides smart HTTP routing, and Network Policies provide security rules. They work together: traffic comes into the cluster through an Ingress, which sends it to a Service, which distributes it to the pods, and Network Policies restrict which pods can talk to each other at every step.

## Real-world context

Imagine you are a platform engineer at a mid-sized e-commerce company. Your team has just migrated the online store to Kubernetes. The application consists of three microservices: a front-end web server (serving the product pages), an order-processing service (handling purchases), and a payment-gateway service (charging credit cards). All of these run in separate pods.

Your first task is to expose the front-end to customers on the internet. You create a LoadBalancer Service pointing to the front-end pods. The cloud provider provisions a public IP address and a load balancer that forwards traffic to any of the front-end pods. Customers visit your website and the traffic flows correctly — that is the Service doing its job.

But the CEO now wants two domains: store.example.com for the public shop and admin.example.com for internal staff ordering. You cannot do this with a Service alone because a Service does not understand hostnames. You need an Ingress. You create an Ingress resource that listens on port 80 and 443. You configure two rules: if the host header says store.example.com, route to the front-end Service; if it says admin.example.com, route to a separate admin Service. The Ingress also handles HTTPS — you upload a TLS certificate, and the Ingress decrypts incoming HTTPS traffic before forwarding it as HTTP to the pods.

Next, security. The payment-gateway service must never accept traffic from the front-end pods directly. Only the order-processing service should talk to it. You write a Network Policy with the following rules:
- Pods with label "app: front-end" can only send traffic to pods with label "app: order-processing".
- Pods with label "app: order-processing" can send traffic to pods with label "app: payment-gateway".
- All other traffic to the payment-gateway is denied.

You apply this Network Policy using kubectl apply -f policy.yaml. Immediately, a developer reports that their debug pod (which they created with a different label) cannot reach the payment service — the policy correctly blocks it. That is Network Policy in action.

Finally, you monitor the system. You notice that the front-end pods sometimes restart due to high traffic. Because you are using a Service with a label selector, new pods are automatically added to the Service's endpoints list — no manual reconfiguration needed. The Ingress continues to route traffic to the Service, and the Service routes to whichever pods are healthy.

This real-world workflow happens daily at thousands of companies. The KCNA exam will test your understanding of exactly these interactions: which Service type to use for which scenario, how Ingress rules differ from Service rules, and how Network Policies limit pod-to-pod communication.

## Exam focus

The KCNA exam focuses on three specific network resources: Services, Ingress, and Network Policies. You will not be asked to write YAML from memory, but you must understand the purpose, behaviour, and correct use of each.

What the exam tests about Services:
- The four types (ClusterIP, NodePort, LoadBalancer, ExternalName) and when to use each.
- How Services use label selectors to find the correct pods.
- That ClusterIP is the default.
- That NodePort opens a high port on every node (30000–32767).
- That LoadBalancer is the typical production choice for external traffic in cloud environments.
- That Services work at Layer 4 (TCP/UDP).

What the exam tests about Ingress:
- That Ingress works at Layer 7 (HTTP/HTTPS) and can route based on host or path.
- That Ingress is not a replacement for Services; it sits in front of them.
- That Ingress can terminate TLS/SSL.
- That you need an Ingress controller (like NGINX Ingress Controller or HAProxy) running in the cluster for the Ingress resource to work.
- That Ingress rules are defined with host and path fields.

What the exam tests about Network Policies:
- That Network Policies are an allow list — they define what is allowed, and anything not explicitly allowed is denied by default.
- That Network Policies are namespace-scoped.
- That they use podSelector and namespaceSelector to select target pods.
- That they support ingress (incoming) and egress (outgoing) rules.
- That the network plugin must support Network Policies (e.g., Calico, Cilium, Weave Net); if it does not, the policy is ignored.

Common traps the exam sets:
- Expecting you to confuse ClusterIP and NodePort: remember, ClusterIP is internal-only, NodePort is external-facing via a high port on all nodes.
- Thinking Ingress replaces Services: it does not — Ingress forwards to a Service, which then forwards to pods.
- Assuming Network Policies deny by default: they actually allow all traffic until you apply a policy. Once a policy targets a pod, only traffic matching that policy is allowed; all other traffic is denied.
- Mixing up port and targetPort in Services: the Service listens on port, and forwards to targetPort on the pod.
- Forgetting that ExternalName Services do not proxy traffic — they return a DNS CNAME record.

Exam-style question patterns you will see:
- "Which Service type should you use to expose a deployment internally to other services in the same cluster?" Answer: ClusterIP.
- "A Network Policy is applied to a pod. What happens to traffic that does not match any rule?" Answer: It is denied.
- "Which resource can route traffic based on the URL path?" Answer: Ingress.
- "What must be installed in the cluster for an Ingress resource to function?" Answer: An Ingress controller.

Memorise the following patterns:
- ClusterIP: internal, default, no external exposure.
- NodePort: external, high port, not production.
- LoadBalancer: cloud-integrated, production, public IP.
- Ingress: Layer 7, host/path routing, needs a controller.
- Network Policy: allow-list, pod/namespace selectors, ingress/egress.

## Step by step

1. **Create a Deployment** — You first define a Deployment that creates and manages your application pods. For example, a YAML file specifying three replicas of a web server pod. This ensures your app runs reliably.
2. **Expose the Deployment with a Service** — You create a Service YAML that targets the pods by their labels (e.g., app: web). The Service receives a stable ClusterIP (internal) or, if type is LoadBalancer, an external IP. Traffic arriving at the Service's IP and port is forwarded to one of the matching pods.
3. **Configure an Ingress for HTTP Routing** — If you need path-based or host-based routing (e.g., /api vs /web), you create an Ingress resource. The Ingress watches for new Services and automatically updates its routing rules. Traffic hits the Ingress controller, which applies the rules and forwards to the correct Service.
4. **Apply Network Policies for Security** — You write a Network Policy YAML that selects specific pods (e.g., front-end) and defines allowed ingress and egress traffic. Using kubectl apply, the policy is activated. Pods matching the selector will now only accept traffic that matches the policy rules; all other traffic is dropped.
5. **Verify Connectivity and Access** — You test the setup: curl the Service's ClusterIP from inside the cluster, hit the LoadBalancer's external IP from a browser, and confirm that blocked traffic (e.g., from an unauthorised pod to the database) fails. This step validates that Services, Ingress, and Network Policies are working together correctly.

## Comparisons

### ClusterIP Service vs NodePort Service

**ClusterIP Service:**
- Only reachable from inside the cluster
- Default Service type
- Used for internal microservice communication

**NodePort Service:**
- Reachable from outside the cluster via a high port on every node
- Not a default type — must be explicitly set
- Used for development or debugging external access

### LoadBalancer Service vs Ingress

**LoadBalancer Service:**
- Operates at Layer 4 (TCP/UDP)
- Provides a single public IP address per Service
- No routing based on host or path — only port forwarding

**Ingress:**
- Operates at Layer 7 (HTTP/HTTPS)
- Can route to multiple Services using a single public IP
- Routes based on hostnames and URL paths

### Ingress Resource vs Ingress Controller

**Ingress Resource:**
- A Kubernetes API object (YAML) that defines routing rules
- Does not handle traffic — just stores rules
- Must be created before the controller can act

**Ingress Controller:**
- A running pod or set of pods (e.g., NGINX) that processes Ingress rules
- Handles actual traffic and configures the reverse proxy
- Must be deployed in the cluster for Ingress resources to work

### Network Policy (Ingress Rule) vs Network Policy (Egress Rule)

**Network Policy (Ingress Rule):**
- Controls traffic coming into the selected pod
- Uses 'from' field to specify allowed sources
- If no ingress rule exists, all inbound traffic to the selected pod is denied

**Network Policy (Egress Rule):**
- Controls traffic leaving the selected pod
- Uses 'to' field to specify allowed destinations
- If no egress rule exists, all outbound traffic from the selected pod is denied

## Diagram

_Flow of traffic from an external client through Ingress, into Services, then to pods, with Network Policies restricting communication between pods._

```mermaid
graph TD
    A[Internet / External Client] --> B[Ingress Controller]
    B --> C[Ingress Resource]
    C --> D[Service: front-end]
    C --> E[Service: back-end]
    D --> F[Pod 1: front-end]
    D --> G[Pod 2: front-end]
    E --> H[Pod 3: back-end]
    E --> I[Pod 4: back-end]
    H -. Network Policy .-> J[Database Pod]
    F -. Network Policy .-> H
    J -. Network Policy .-> K[External API]
```

## Common misconceptions

- **Misconception:** A Service automatically makes an application accessible from the internet. **Reality:** Only NodePort and LoadBalancer types expose the Service externally. ClusterIP is internal-only, and ExternalName returns a DNS record without proxying traffic. (Beginners assume every IP address is public, but Kubernetes defaults to internal connectivity.)
- **Misconception:** An Ingress replaces the need for a Service. You can point an Ingress directly to pods. **Reality:** An Ingress always routes traffic to a Service, not directly to pods. The Service then forwards traffic to the pods. (The name 'Ingress' sounds like 'entry point', so people think it is the only thing needed, but it is one layer in a stack.)
- **Misconception:** Network Policies block all traffic by default, just like a firewall. **Reality:** Network Policies are allow-lists. If no policy targets a pod, all traffic is allowed. Once a policy targets a pod, only matching traffic is allowed; everything else is denied. (Many people come from traditional firewall environments where everything is denied unless explicitly allowed, but Kubernetes starts with open communication.)
- **Misconception:** All network plugins in Kubernetes support Network Policies. **Reality:** Only certain network plugins (e.g., Calico, Cilium, Weave Net) implement Network Policies. Plugins like Flannel (default in some distributions) do not enforce Network Policies, meaning the policies are ignored if you apply them. (Kubernetes is modular; the core does not enforce Network Policies — the CNI plugin must support them.)
- **Misconception:** A NodePort Service only exposes the application on a single node. **Reality:** A NodePort Service exposes the same port on every node in the cluster. Traffic reaching any node's IP on that port is forwarded to the Service and then to a pod. (The word 'Node' in NodePort leads beginners to think it is per-node, but it is actually cluster-wide.)

## Key takeaways

- A Service provides a stable IP address and DNS name that remains unchanged even when pods are created or destroyed.
- ClusterIP Services are only accessible from within the cluster; use LoadBalancer for external production traffic.
- Ingress operates at Layer 7 and can route traffic based on hostnames and URL paths, making it essential for multi-domain applications.
- Network Policies are allow-list rules; if a pod has a policy, any traffic not explicitly allowed is denied.
- For a Network Policy to work, your cluster must use a CNI plugin that supports policy enforcement, such as Calico or Cilium.
- An Ingress resource requires an Ingress controller — a separate pod that reads the rules and configures the proxy.

## FAQ

**What is the difference between a Service and a Deployment in Kubernetes?**

A Deployment manages the lifecycle of your application pods (creating, scaling, updating). A Service provides a stable network endpoint to reach those pods. You need both: the Deployment creates the pods, the Service makes them discoverable.

**Can I use a Service without selecting any pods?**

Technically yes, but the Service will have no endpoints and traffic will be dropped. You can use this to create a Service that points to an external resource (using ExternalName) or to a manually maintained list of endpoints (Endpoints object).

**Why does my Ingress resource not do anything after I create it?**

You likely do not have an Ingress controller running in your cluster. The Ingress resource is just a set of rules — you need a controller like NGINX Ingress Controller, Traefik, or HAProxy to actually implement those rules by configuring a reverse proxy.

**If I create a Network Policy, will it affect pods that I created before the policy?**

Yes. Network Policies are applied to pods based on their labels at the moment the policy is created. Existing pods with matching labels will immediately start enforcing the policy.

**What happens if my CNI plugin does not support Network Policies?**

The Network Policy resource will be accepted by the Kubernetes API server, but it will have no effect — traffic will continue to flow as if no policy existed. You must choose a CNI plugin that supports policies, such as Calico, Cilium, or Weave Net.

**Can I use multiple Services for the same set of pods?**

Yes, you can create multiple Services that select the same pods using the same label selector. This is useful when you want both an internal ClusterIP Service and an external LoadBalancer Service pointing to the same application.

## Check your understanding

1. **Which Service type is used to expose a deployment internally to other services in the same Kubernetes cluster?**

   Answer: ClusterIP. It provides an internal IP address that is only reachable from within the cluster.

2. **What must be running in a cluster for an Ingress resource to actually route traffic?**

   Answer: An Ingress controller, such as NGINX Ingress Controller or Traefik, must be deployed in the cluster.

3. **What happens by default to traffic that is not explicitly allowed by a Network Policy when a policy is applied to a pod?**

   Answer: The traffic is denied. Network Policies are allow-lists; anything not allowed is blocked.

4. **A customer needs to route traffic to different Services based on the URL path (e.g., /api vs /web). Which resource should they use?**

   Answer: An Ingress resource, because it operates at Layer 7 and supports path-based routing.

5. **You have a legacy database running outside your Kubernetes cluster. Which Service type can you use to give it a stable DNS name inside the cluster?**

   Answer: ExternalName Service. It returns a CNAME record pointing to the external database's DNS name without proxying traffic.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/cncf-kcna/services-and-networking
