Services, Load Balancing, and Network Policies
local graph
Chapter 4 — Services, Load Balancing, and Network Policies
Section titled “Chapter 4 — Services, Load Balancing, and Network Policies”In the previous chapter, we kicked off our Kubernetes Bootcamp to give you a quick but thorough introduction to Kubernetes basics and objects. We started by breaking down the main parts of a Kubernetes cluster, focusing on the control plane and worker nodes. The control plane is the brain of the cluster, managing everything including scheduling tasks, creating deployments, and keeping track of Kubernetes objects. The worker nodes are used to run the applications, including components like the kubelet service, keeping the containers healthy, and kube-proxy to handle the network connections.
We looked at how you interact with a cluster using the kubectl tool, which lets you run commands directly or use YAML or JSON manifests to declare what you want Kubernetes to do. We also explored most Kubernetes resources. Some of the more common resources we discussed included DaemonSets, which ensure a pod runs on all or specific nodes, StatefulSets to manage stateful applications with stable network identities and persistent storage, and ReplicaSets to keep a set number of pod replicas running.
The Bootcamp chapter should have helped to provide a solid understanding of Kubernetes architecture, its key components and resources, and basic resource management. Having this base knowledge sets you up for the more advanced topics in the next chapters.
In this chapter, you’ll learn how to manage and route network traffic to your Kubernetes services. We’ll begin by explaining the fundamentals of load balancers and how to set them up to handle incoming requests to access your applications. You’ll understand the importance of using service objects to ensure reliable connections to your pods, despite their ephemeral IP addresses.
Additionally, we’ll cover how to expose your web-based services to external traffic using an Ingress controller, and how to use LoadBalancer services for more complex, non-HTTP/S workloads. You’ll get hands-on experience by deploying a web server to see these concepts in action.
Since many readers are unlikely to have a DNS infrastructure to facilitate name resolution, which is required for Ingress to work, we will manage DNS names using a free internet service, nip.io.
Finally, we’ll explore how to secure your Kubernetes services using network policies, ensuring both internal and external communications are protected.
The following topics will be covered in this chapter:
- Introduction to load balancers and their role in routing traffic.
- Understanding service objects in Kubernetes and their importance.
- Exposing web-based services using an Ingress controller.
- Using
LoadBalancerservices for complex workloads. - Deploying an NGINX Ingress controller and setting up a web server.
- Utilizing the nip.io service for managing DNS names.
- Securing services with network policies to protect communications.
As this chapter ends, you will understand deeply the various methods to expose and secure your workloads in a Kubernetes cluster.
Technical requirements
Section titled “Technical requirements”This chapter has the following technical requirements:
- An Ubuntu 22.04+ server running Docker with a minimum of 4 GB of RAM, though 8 GB is suggested.
- Scripts from the
chapter4folder from the repository, which you can access by going to this book’s GitHub repository: https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition.
Exposing workloads to requests
Section titled “Exposing workloads to requests”Through our experience, we’ve come to realize that there are three concepts in Kubernetes that people may find confusing: Services, Ingress controllers, and LoadBalancer Services. These are important to know in order to make your workloads accessible to the outside world. Understanding how each of these objects function and the various options you have, is crucial. So, let’s start our deep dive into each of these topics.
Understanding how Services work
Section titled “Understanding how Services work”As we mentioned earlier, when a workload is running in a pod, it gets assigned an IP address. However, there are situations where a pod might restart, and when that happens, it will get a new IP address. So, it’s not a good idea to directly target a pod’s workload because its IP address can change.
One of the coolest things about Kubernetes is its ability to scale your Deployments. When you scale a Deployment, Kubernetes adds more pods to handle the increased resource requirements. Each of these pods gets its own unique IP address. But here’s the thing: most applications are designed to target only one IP address or name.
Imagine if your application went from running just one pod to suddenly running 10 pods due to scaling. How would you make use of these additional pods since you can only target a single IP address? That’s what we’re going to explore next.
Services in Kubernetes utilize labels to create a connection between the service and the pods handling the workload. When pods start up, they are assigned labels, and all pods with the same label, as defined in the deployment, are grouped together.
Let’s take an NGINX web server as an example. In our Deployment, we would create a manifest like this:
apiVersion: apps/v1kind: Deploymentmetadata: labels: run: nginx-frontend name: nginx-frontendspec: replicas: 3 selector: matchLabels: run: nginx-frontend template: metadata: labels: run: nginx-frontend spec: containers: - image: bitnami/nginx name: nginx-frontendThis deployment will create three NGINX servers and each pod will be labeled with run=nginx-frontend. We can verify whether the pods are labeled correctly by listing the pods using kubectl, and adding the --show-labels option, kubectl get pods --show-labels.
This will list each pod and any associated labels:
nginx-frontend-6c4dbf86d4-72cbc 1/1 Running 0 19s pod-template-hash=6c4dbf86d4,run=nginx-frontendnginx-frontend-6c4dbf86d4-8zlwc 1/1 Running 0 19s pod-template-hash=6c4dbf86d4,run=nginx-frontendnginx-frontend-6c4dbf86d4-xfz6m 1/1 Running 0 19s pod-template-hash=6c4dbf86d4,run=nginx-frontendIn the example, each pod is given a label called run=nginx-frontend. This label plays a crucial role when configuring the service for your application. By leveraging this label in the service configuration, the service will automatically generate the required endpoints without manual intervention.
Creating a Service
Section titled “Creating a Service”In Kubernetes, a Service is a way to make your application accessible to other programs or users. Think of it like a gateway or an entry point to your application.
There are four different types of services in Kubernetes, and each type serves a specific purpose. We will go into the details of each type in this chapter, but for now, let’s take a look at them in simple terms:
| Service Type | Description |
|---|---|
ClusterIP | Creates a service that is accessible from inside of the cluster. |
NodePort | Creates a service that is accessible from inside or outside of the cluster using an assigned port. |
LoadBalancer | Creates a service that is accessible from inside or outside of the cluster. For external access, an additional component is required to create the load-balanced object. |
ExternalName | Creates a service that does not target an endpoint in the cluster. Instead, it is used to provide a service name that targets any external DNS name as an endpoint. |
Table 4.1: Kubernetes service types
There is an additional service type that can be created, known as a headless service. A Kubernetes Headless Service is a service type that enables direct communication with individual pods instead of distributing traffic across them like other services. Unlike regular Services that assign a single, fixed IP address to a group of pods, a Headless Service doesn’t assign a cluster IP.
A Headless Service is created by specifying none for the clusterIP spec in the Service definition.
To create a service, you need to create a Service object that includes kind, selector, type, and any ports that will be used to connect to the service. For our NGINX Deployment example, we want to expose the Service on ports 80 and 443. We labeled the deployment with run=nginx-frontend, so when we create a manifest, we will use that name as our selector:
apiVersion: v1kind: Servicemetadata: labels: run: nginx-frontend name: nginx-frontendspec: selector: run: nginx-frontend ports: - name: http port: 80 protocol: TCP targetPort: 80 - name: https port: 443 protocol: TCP targetPort: 443 type: ClusterIPIf a type is not defined in a service manifest, Kubernetes will assign a default type of ClusterIP.
Now that a service has been created, we can verify that it was correctly defined using a few kubectl commands. The first check we will perform is to verify that the service object was created. To check our service, we use the kubectl get services command:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEnginx-frontend ClusterIP 10.43.142.96 <none> 80/TCP,443/TCP 3m49sAfter verifying that the service has been created, we can verify that the Endpoints / Endpointslices were created. Remember from the Bootcamp chapter that Endpoints are any pod that have a matching label that we used in our service. Using kubectl, we can verify the Endpoints by executing kubectl get ep <service name>:
NAME ENDPOINTSnginx-frontend 10.42.129.9:80,10.42.170.91:80,10.42.183.124:80 + 3 more...We can see that the Service shows three Endpoints, but it also shows +3 more in the endpoint list. Since the output is truncated, the output from a get is limited and it cannot show all of the endpoints. Since we cannot see the entire list, we can get a more detailed list if we describe the endpoints. Using kubectl, you can execute the kubectl describe ep <service name> command:
Name: nginx-frontendNamespace: defaultLabels: run=nginx-frontendAnnotations: endpoints.kubernetes.io/last-change-trigger-time: 2020-04-06T14:26:08ZSubsets: Addresses: 10.42.129.9,10.42.170.91,10.42.183.124 NotReadyAddresses: <none> Ports: Name Port Protocol ---- ---- -------- http 80 TCP https 443 TCPEvents: <none>If you compare the output from our get and describe commands, it may appear that there is a mismatch in the Endpoints. The get command showed a total of six Endpoints: it showed three IP Endpoints and, because it was truncated, it also listed +3, for a total of six Endpoints. The output from the describe command shows only three IP addresses, and not six. Why do the two outputs appear to show different results?
The get command will list each endpoint and port in the list of addresses. Since our service is defined to expose two ports, each address will have two entries, one for each exposed port. The address list will always contain every socket for the service, which may list the endpoint addresses multiple times, once for each socket.
The describe command handles the output differently, listing the addresses on one line with all of the ports listed below the addresses. At first glance, it may look like the describe command is missing three addresses, but since it breaks the output into multiple sections, it will only list the addresses once. All ports are broken out below the address list; in our example, it shows ports 80 and 443.
Both commands show similar data, but it is presented in a different format.
Now that the service is exposed to the cluster, you could use the assigned service IP address to connect to the application. While this would work, the address may change if the Service object is deleted and recreated. So, rather than targeting an IP address, you should use the DNS that was assigned to the service when it was created.
In the next section, we will explain how to use internal DNS names to resolve services.
Using DNS to resolve services
Section titled “Using DNS to resolve services”So far, we have shown you that when you create certain objects in Kubernetes, the object will be assigned an IP address. The problem is that when you delete an object like a pod or service, there is a high likelihood that when you redeploy that object, it will receive a different IP address. Since IPs are transient in Kubernetes, we need a way to address objects with something other than a changing IP address. This is where the built-in DNS service in Kubernetes clusters comes in.
When a service is created, an internal DNS record is automatically generated, allowing other workloads within the cluster to query it by name. If all pods reside in the same namespace, we can conveniently access the services using a simple, short name like mysql-web. However, in cases where services are utilized by multiple namespaces, and workloads need to communicate with a service in a different namespace, the service must be targeted using its full name.
The following table provides an example of how a service may be accessed from various namespaces:
Cluster name: Target Service: Target Service | |
Pod Namespace | Valid Names to Connect to the MySQL Service |
|
|
|
|
|
|
Table 4.2: Internal DNS examples
As you can see from the preceding table, you can target a service that is in another namespace by using a standard naming convention, .<namespace>.svc.<cluster name>. In most cases, when you are accessing a service in a different namespace, you do not need to add the cluster name, since it should be appended automatically.
To expand on the overall concept of services, let’s dive into the specifics of each service type and explore how they can be used to access our workloads.
Understanding different service types
Section titled “Understanding different service types”When you create a service, you can specify a service type, but if you do not specify a type, the ClusterIP type will be used by default. The service type that is assigned will configure how the service is exposed to either the cluster itself or external traffic.
The ClusterIP service
Section titled “The ClusterIP service”The most commonly used, and often misunderstood, service type is ClusterIP. If you look back at Table 4.1, you can see that the description for the ClusterIP type states that the service allows connectivity to the service from within the cluster. The ClusterIP type does not allow any external communication to the exposed service.
The idea of exposing a service to only internal cluster workloads can be a confusing concept. In the next example, we will describe a use case where exposing a service to just the cluster itself makes sense and also increases security.
For a moment, let’s set aside external traffic and focus on our current deployment. Our main goal is to understand how each component works together to form our application. Taking the NGINX example, we will enhance the deployment by adding a backend database that is used by the web server.
So far, this is a simple application: we have our deployments created, a service for the NGINX servers called web frontend, and a database service called mysql-web. To configure the database connection from the web servers, we have decided to use a ConfigMap that will target the database service.
You may be thinking that since we are using a single database server, we could simply use the IP address of the pod. While this would initially work, any restarts to the pod would change the address and the web servers would fail to connect to the database. Since pod IPs are ephemeral, a service should always be used, even if you are only targeting a single pod.
While we may want to expose the web server to external traffic at some point, why would we need to expose the mysql-web database service? Since the web server is in the same cluster, and in this case, the same namespace, we only need to use a ClusterIP address type so the web server can connect to the database server. Since the database is not accessible from outside of the cluster, it’s more secure since it doesn’t allow any traffic from outside the cluster.
By using the service name instead of the pod IP address, we will not run into issues when the pod is restarted since the service targets the labels rather than an IP address. Our web servers will simply query the Kubernetes DNS server for the mysql-web service name, which will contain the endpoints of any pod that matches the mysql-web label.
The NodePort service
Section titled “The NodePort service”A NodePort service provides both internal and external access to your service within the cluster. At first, it may seem like the ideal choice for exposing a service since it makes it accessible to everyone. However, it achieves this by assigning a port on the node (which, by default uses a port in the range of 30000-32767). Relying on a NodePort can be confusing for users when they need to access a service over the network since they need to remember the specific port that was assigned to the service. You will see how you access a service on a NodePort shortly, demonstrating why we do not suggest using it for production workloads.
While in most enterprise environments, you shouldn’t use a NodePort service for any production workloads, there are some valid reasons to use them, primarily, to troubleshoot accessing a workload. When we receive a call from an application that has an issue, and the Kubernetes platform or Ingress controller is being blamed, we may temporarily change the service from ClusterIP to NodePort to test connectivity without using an Ingress Controller. By accessing the application using a NodePort, we bypass the Ingress controller, taking that component out of the equation as a potential source causing the issue. If we are able to access the workload using the NodePort and it works, we know the issue isn’t with the application itself and can direct engineering resources to look at the Ingress controller or other potential root causes.
To create a service that uses the NodePort type, you just need to set the type to NodePort in your manifest. We can use the same manifest that we used earlier to expose an NGINX deployment from the ClusterIP example, only changing type to NodePort:
apiVersion: v1kind: Servicemetadata: labels: run: nginx-frontend name: nginx-frontendspec: selector: run: nginx-frontend ports: - name: http port: 80 protocol: TCP targetPort: 80 - name: https port: 443 protocol: TCP targetPort: 443 type: NodePortWe can view the endpoints in the same way that we did for a ClusterIP service, using kubectl. Running kubectl get services will show you the newly created service:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEnginx-frontend NodePort 10.43.164.118 <none> 80:31574/TCP,443:32432/TCP 4sThe output shows that the type is NodePort and that we have exposed the service IP address and the ports. If you look at the ports, you will notice that, unlike a ClusterIP service, a NodePort service shows two ports rather than one. The first port is the exposed port that the internal cluster services can target, and the second port number is the randomly generated port that is accessible from outside of the cluster.
Since we exposed both ports 80 and 443 for the service, we will have two NodePorts assigned. If someone needs to target the service from outside of the cluster, they can target any worker node with the supplied port to access the service.

Figure 6.1 – NGINX service using NodePort
Figure 4.1: NGINX service using NodePort
Each node maintains a list of the NodePorts and their assigned services. Since the list is shared with all nodes, you can target any functioning node using the port and Kubernetes will route it to a running pod.
To visualize the traffic flow, we have created a graphic showing the web request to our NGINX pod:

Figure 6.2 – NodePort traffic flow overview
Figure 4.2: NodePort traffic flow overview
There are some issues to consider when using a NodePort to expose a service:
- If you delete and recreate the service, the assigned
NodePortwill change. - If you target a node that is offline or having issues, your request will fail.
- Using
NodePortfor too many services may get confusing. You need to remember the port for each service and remember that there are no external names associated with the service. This may get confusing for users who are targeting services in the cluster.
Because of the limitations listed here, you should limit using NodePort services.
The LoadBalancer service
Section titled “The LoadBalancer service”Many people starting in Kubernetes read about services and discover that the LoadBalancer type will assign an external IP address to a service. Since an external IP address can be addressed directly by any machine on the network, this is an attractive option for a service, which is why many people try to use it first. Unfortunately, since many users may start by using an on-premises Kubernetes cluster, they run into failures trying to create a LoadBalancer service.
The LoadBalancer service relies on an external component that integrates with Kubernetes to create the IP address assigned to the service. Most on-premises Kubernetes installations do not include this type of service. Without the additional components, when you try to use a LoadBalancer service, you will find that your service shows <pending> in the EXTERNAL-IP status column.
We will explain the LoadBalancer service and how to implement it later in the chapter.
The ExternalName service
Section titled “The ExternalName service”The ExternalName service is a unique service type with a specific use case. When you query a service that uses an ExternalName type, the final endpoint is not a pod that is running in the cluster, but an external DNS name.
To use an example that you may be familiar with outside of Kubernetes, this is similar to using c-name to alias a host record. When you query a c-name record in DNS, it resolves to a host record rather than an IP address.
Before using this service type, you need to understand the potential issues that it may cause for your application. You may run into issues if the target endpoint is using SSL certificates. Since the hostname you are querying may not be the same as the name on the destination server’s certificate, your connection may not succeed because of the name mismatch. If you find yourself in this situation, you may be able to use a certificate that has subject alternative names (SANs) added to the certificate. Adding alternative names to a certificate allows you to associate multiple names with a certificate.
To explain why you may want to use an ExternalName service, let’s use the following example:
FooWidgets application requirements
FooWidgets is running an application on their Kubernetes cluster that needs to connect to a database server running on a Windows 2019 server called sqlserver1.foowidgets.com (192.168.10.200).
The current application is deployed to a namespace called finance.
The SQL server will be migrated to a container in the next quarter.
You have two requirements:
- Configure the application to use the external database server using only the cluster’s DNS server.
- FooWidgets cannot make any configuration changes to the applications after the SQL server is migrated.
Based on the requirements, using an ExternalName service is the perfect solution. So, how would we accomplish the requirements? (This is a theoretical exercise; you do not need to execute anything on your KinD cluster.) Here are the steps:
- The first step is to create a manifest that will create the
ExternalNameservice for the database server:apiVersion: v1kind: Servicemetadata:name: sql-dbnamespace: financespec:type: ExternalNameexternalName: sqlserver1.foowidgets.com - With the service created, the next step is to configure the application to use the name of our new service. Since the service and the application are in the same namespace, you can configure the application to target the
sql-dbname. - Now, when the application queries for
sql-db, it will resolve tosqlserver1.foowidgets.com, which will forward the DNS request to an external DNS server where the name is resolved to the IP address of192.168.10.200.
This accomplishes the initial requirement, connecting the application to the external database server using only the Kubernetes DNS server.
You may be wondering why we didn’t simply configure the application to use the database server name directly. The key is the second requirement; limiting any reconfiguration when the SQL server is migrated to a container.
Since we cannot reconfigure the application once the SQL server is migrated to the cluster, we will not be able to change the name of the SQL server in the application settings. If we configured the application to use the original name, sqlserver1.foowidgets.com, the application would not work after the migration. By using the ExternalName service, we can change the internal DNS service name by replacing the ExternalHost service name with a standard Kubernetes service that points to the SQL server.
To accomplish the second goal, go through the following steps:
- Since we have created a new entry in DNS for the
sql-dbname, we should delete theExternalNameservice, since it is no longer needed. - Create a new service using the name
sql-dbthat usesapp=sql-appas the selector. The manifest would look like the one shown here:apiVersion: v1kind: Servicemetadata:labels:app: sql-dbname: sql-dbnamespace: financespec:ports:- port: 1433protocol: TCPtargetPort: 1433name: sqlselector:app: sql-apptype: ClusterIP
Since we are using the same service name for the new service, no changes need to be made to the application. The app will still target the sql-db name, which will now use the SQL server deployed in the cluster.
Now that you know about services, we can move on to load balancers, which will allow you to expose services externally using standard URL names and ports.
Introduction to load balancers
Section titled “Introduction to load balancers”In this second section, we will discuss the basics between utilizing layer 7 and layer 4 load balancers. To understand the differences between the types of load balancers, it’s important to understand the Open Systems Interconnection (OSI) model. Understanding the different layers of the OSI model will help you to understand how different solutions handle incoming requests.
Understanding the OSI model
Section titled “Understanding the OSI model”There are various approaches for exposing an application in Kubernetes, and you’ll frequently come across mentions of layer 7 or layer 4 load balancing. These terms indicate the positions they hold in the OSI model, with each layer providing a distinct functionality. Each component that operates in layer 7 will offer different capabilities compared to those at layer 4.
To begin, let’s look at a brief overview of the seven layers and a description of each. For this chapter, we are interested in the two highlighted sections, layer 4 and layer 7:
| OSI Layer | Name | Description |
|---|---|---|
| 7 | Application | Provides application traffic, including HTTP and HTTPS |
| 6 | Presentation | Forms data packets and encryption |
| 5 | Session | Controls traffic flow |
| 4 | Transport | Communication traffic between devices, including TCP and UDP |
| 3 | Network | Routing between devices, including IP |
| 2 | Data Link | Performs error checking for physical connection (MAC address) |
| 1 | Physical | Physical connection of devices |
Table 4.3: OSI model layers
You don’t need to be an expert in the OSI layers, but you should understand what layer 4 and layer 7 load balancers provide and how each may be used with a cluster.
Let’s go deeper into the details of layers 4 and 7:
- Layer 4: As the description states in the chart, layer 4 is responsible for the communication of traffic between devices. Devices that run at layer 4 have access to TCP/UDP information. Load balancers that are layer-4-based provide your applications with the ability to service incoming requests for any TCP/UDP port.
- Layer 7: Layer 7 is responsible for providing network services to applications. When we say application traffic, we are not referring to applications such as Excel or Word; instead, we are referring to the protocols that support the applications, such as HTTP and HTTPS.
This may be very new for some people and to completely understand each of the layers would require multiple chapters – which is beyond the scope of this book. The main point we want you to take away from this introduction is that applications like databases cannot be exposed externally using a layer 7 load balancer. To expose an application that does not use HTTP/S traffic requires the use of a layer 4 load balancer.
In the next section, we will explain each load balancer type and how to use them in a Kubernetes cluster to expose your services.
Layer 7 load balancers
Section titled “Layer 7 load balancers”Kubernetes offers Ingress controllers as layer 7 load balancers, which provide a means of accessing your applications. Various options are available for enabling Ingress in your Kubernetes clusters, including the following:
- NGINX
- Envoy
- Traefik
- HAProxy
You can think of a layer 7 load balancer as a traffic director for networks. Its role is to distribute incoming requests to multiple servers hosting a website or application.
When you access a website or use an app, your device sends a request to the server asking for the specific web page or data you want. With a layer 7 load balancer, your request doesn’t directly reach a single server, instead, it sends the traffic through the load balancer. The layer 7 load balancer examines the content of your request and understands what web page or data is being requested. Using factors like backend server health, current workload, and even your location, the load balancer intelligently selects the best servers to handle your request.
A layer 7 load balancer ensures that all servers are utilized efficiently, and users receive a smooth and responsive experience. Think of this like being at a store that has multiple checkout counters where a store manager guides customers to the least busy checkout, minimizing waiting times and ensuring everyone gets served promptly.
To recap, layer 7 load balancers optimize the overall system performance and reliability.
Name resolution and layer 7 load balancers
Section titled “Name resolution and layer 7 load balancers”To handle layer 7 traffic in a Kubernetes cluster, you deploy an Ingress controller. Ingress controllers are dependent on incoming names to route traffic to the correct service. This is much easier and faster than in a legacy server deployment model where you would need to create a DNS entry and map it to an IP address before users could access the application externally by name.
Applications that are deployed on a Kubernetes cluster are no different—the users will use an assigned DNS name to access the application. The most common implementation is to create a new wildcard domain that will target the Ingress controller via an external load balancer, such as an F5, HAProxy, or Seesaw. A wildcard domain will direct all traffic for a given domain to the same destination. For example, if your wildcard domain name is foowidgets.com, your main entry in the domain would be *.foowidgets.com. Any ingress URL name that is assigned using the wildcard domain will have the traffic directed to the external load balancer, where it will be directed to the defined service using your ingress rule URL.
Using the foowidgets.com domain as an example, we have three Kubernetes clusters, fronted by an external load balancer with multiple Ingress controller endpoints. Our DNS server would have entries for each cluster, using a wildcard domain that points to the load balancer’s virtual IP address:
| Domain Name | IP Address | K8s Cluster |
|---|---|---|
*.clusterl.foowidgets.com | 192.168.200.100 | Production001 |
*.cluster2.foowidgets.com | 192.168.200.101 | Production002 |
*.cluster3.foowidgets.com | 192.168.200.102 | Development001 |
Table 4.4: Example of wildcard domain names for Ingress
The following diagram shows the entire flow of the request:

Figure 6.3 – Multiple-name Ingress traffic flow
Figure 4.3: Multiple-name Ingress traffic flow
Each of the steps in Figure 4.3 is detailed here:
- Using a browser, the user requests this URL:
https://timesheets.cluster1.foowidgets.com. - The DNS query is sent to a DNS server. The DNS server looks up the zone details for
cluster1.foowidgets.com. There is a single entry in the DNS zone that resolves to the virtual IP (VIP) address, assigned on the load balancer for the domain. - The load balancer’s VIP for
cluster1.foowidgets.comhas three backend servers assigned, pointing to three worker nodes where we have deployed Ingress controllers. - Using one of the endpoints, the request is sent to the Ingress controller.
- The Ingress controller will compare the requested URL to a list of Ingress rules. When a matching request is found, the Ingress controller will forward the request to the service that was assigned to the Ingress rule.
To help reinforce how Ingress works, it will help to create Ingress rules on a cluster to see them in action. Right now, the key takeaway is that ingress uses the requested URL to direct traffic to the correct Kubernetes services.
Using nip.io for name resolution
Section titled “Using nip.io for name resolution”Many personal development clusters, such as our KinD installation, may not have access to a DNS infrastructure or the necessary permissions to add records. To test Ingress rules, we need to target unique hostnames that are mapped to Kubernetes services by the Ingress controller. Without a DNS server, you need to create a localhost file with multiple names pointing to the IP address of the Ingress controller.
For example, if you deployed four web servers, you would need to add all four names to your local hosts. An example of this is shown here:
192.168.100.100 webserver1.test.local192.168.100.100 webserver2.test.local192.168.100.100 webserver3.test.local192.168.100.100 webserver4.test.localThis can also be represented on a single line rather than multiple lines:
192.168.100.100 webserver1.test.local webserver2.test.local webserver3.test.local webserver4.test.localIf you use multiple machines to test your deployments, you will need to edit the host file on every machine that you plan to use for testing. Maintaining multiple files on multiple machines is an administrative nightmare and will lead to issues that will make testing a challenge.
Luckily, there are free DNS services available that we can use without configuring a complex DNS infrastructure for our KinD cluster.
nip.io is the service that we will use for our KinD cluster name resolution requirements. Using our previous web server example, we will not need to create any DNS records. We still need to send the traffic for the different servers to the NGINX server running on 192.168.100.100 so that Ingress can route the traffic to the appropriate service. nip.io uses a naming format that includes the IP address in the hostname to resolve the name to an IP. For example, say that we have four web servers that we want to test called webserver1, webserver2, webserver3, and webserver4, with Ingress rules on an Ingress controller running on 192.168.100.100.
As we mentioned earlier, we do not need to create any records to accomplish this. Instead, we can use the naming convention to have nip.io resolve the name for us. Each of the web servers would use a name with the following naming standard:
<desired name>.<INGRESS IP>.nip.io
The names for all four web servers are listed in the following table:
| Web Server Name | Nip.io DNS Name |
|---|---|
webserverl | webserver1.192.168.100.100.nip.io |
webserver2 | webserver2.192.168.100.100.nip.io |
webserver3 | webserver3.192.168.100.100.nip.io |
webserver4 | webserver4.192.168.100.100.nip.io |
Table 4.5: nip.io example domain names
When you use any of the preceding names, nip.io will resolve them to 192.168.100.100. You can see an example ping for each name in the following screenshot:

Figure 6.4 – Example name resolution using nip.io
Figure 4.4: Example name resolution using nip.io
Keep in mind that Ingress rules require unique names to properly route traffic to the correct service. Although knowing the IP address of the server might not be required in some scenarios, it becomes essential for Ingress rules. Each name should be unique and typically uses the first part of the full name. In our example, the unique names are webserver1, webserver2, webserver3, and webserver4.
By providing this service, nip.io allows you to use any name for Ingress rules without the need to have a DNS server in your development cluster.
Now that you know how to use nip.io to resolve names for your cluster, let’s explain how to use a nip.io name in an Ingress rule.
Creating Ingress rules
Section titled “Creating Ingress rules”Remember, ingress rules use names to route the incoming request to the correct service.
The following is a graphical representation of an incoming request showing how Ingress routes the traffic:

Figure 6.5 – Ingress traffic flow
Figure 4.5: Ingress traffic flow
Figure 4.5 shows a high-level overview of how Kubernetes handles incoming Ingress requests. To help explain each step in more depth, let’s go over the five steps in greater detail. Using the graphic provided in Figure 4.5, we will explain each numbered step in detail to show how ingress processes the request:
- The user requests a URL in their browser named
http://webserver1.192.168.200.20.nio.io. A DNS request is sent to the local DNS server, which is ultimately sent to thenip.ioDNS server. - The
nip.ioserver resolves the domain name to the192.168.200.20IP address, which is returned to the client. - The client sends the request to the Ingress controller, which is running on
192.168.200.20. The request contains the complete URL name,webserver1.192.168.200.20.nio.io. - The Ingress controller looks up the requested URL name in the configured rules and matches the URL name to a service.
- The service endpoints will be used to route traffic to the assigned pods.
- The request is routed to an endpoint pod running the web server.
Using the preceding example traffic flow, let’s create an NGINX pod, service, and Ingress rule to see this in action. In the chapter4/ingress directory, we have provided a script called nginx-ingress.sh, which will deploy the web server and expose it using an ingress rule of webserver.w.x.y.nip.io. When you execute the script, it will output the complete URL you can use to test the ingress rule.
The script will execute the following steps to create our new NGINX deployment and expose it using an ingress rule:
- A new NGINX deployment called
nginx-webis deployed, using port8080for the web server. - We create a service, called
nginx-web,using aClusterIPservice (the default) on port8080. - The IP address of the host is discovered and used to create a new ingress rule that will use the hostname
webserver.w.x.y.z.nip.io.Thew.x.y.zweb server will be replaced with the IP address of your host.
Once deployed, you can test the web server by browsing to it from any machine on your local network using the URL that is provided by the script. In our example, the host’s IP address is 192.168.200.20, so our URL will be webserver.192.168.200.20.nip.io.

Figure 6.6 – NGINX web server using nip.io for Ingress
Figure 4.6: NGINX web server using nip.io for Ingress
With the details provided in this section, it is possible to generate ingress rules for multiple containers utilizing unique hostnames. It’s important to note that you aren’t restricted to using a service like nip.io for name resolution; you can employ any name resolution method that is accessible in your environment. In a production cluster, you would typically have an enterprise DNS infrastructure. However, in a lab environment, like our KinD cluster, nip.io serves as an excellent tool for testing scenarios that demand accurate naming conventions.
Since we, will use nip.io naming standards throughout the book, so it’s important to understand the naming convention before moving on to the next chapter.
Resolving Names in Ingress Controllers
Section titled “Resolving Names in Ingress Controllers”As discussed earlier, Ingress controllers are primarily level 7 load balancers and are mostly concerned with HTTP/S. How does an Ingress controller get the name of the host? You might think it’s included in the network requests, but it isn’t. A DNS name is used by the client, but at the networking layer, there are no names, only IP addresses.
So, how does the Ingress controller know what host you want to connect to? It depends on whether you’re using HTTP or HTTPS. If you’re using HTTP, your Ingress controller will get the hostname from the Host HTTP header. For instance, here’s a simple request from an HTTP client to a cluster:
GET / HTTP/1.1Host: k8sou.apps.192-168-2-14.nip.ioUser-Agent: curl/7.88.1Accept: */*The second line tells the Ingress controller which host, and which Service, you want the request to go to. This is trickier with HTTPS because the connection is encrypted and the decryption needs to happen before you can read the Host header.
You’ll find that when using HTTPS, your Ingress controller will serve different certificates based on which Service you want to connect to, also based on hostnames. In order to route without yet having access to the Host HTTP header, your Ingress controller will use a protocol called Server Name Indication (SNI), which includes the requested hostname as part of the TLS key exchange. Using SNI, your Ingress controller is able to determine which Ingress configuration object applies to a request before the request is decrypted.
Using Ingress Controllers for non-HTTP traffic
Section titled “Using Ingress Controllers for non-HTTP traffic”The use of SNI offers an interesting side effect, which means that Ingress controllers can sort of pretend to be level 4 load balancers when using TLS. Most Ingress controllers offer a feature called TLS passthrough, where instead of decrypting the traffic, the Ingress controller simply routes it to a Service based on the request’s SNI. Using our earlier example of a web server’s backend database, if you were to configure your Ingress object with a TLS passthrough annotation (which is different for each controller) you could then expose your database through your Ingress.
Given how easy it is to create Ingress objects, you may think this is a security issue. That’s why so much of this book is dedicated to security. It’s quite easy to misconfigure your environment!
A major disadvantage to using TLS passthrough, outside of potential security issues, is that you lose many of your Ingress controller’s native routing and control functions. For instance, if you’re deploying a web application that maintains its own session state, you generally will configure your Ingress object to use sticky sessions so that each user’s request goes back to the same container. This is accomplished by embedding cookies into HTTP responses, but if the controller is just passing the traffic through, it can’t do that.
Layer 7 load balancers, like NGINX Ingress, are commonly deployed for various workloads, including web servers. However, other deployments might require a more sophisticated load balancer, operating at a lower layer of the OSI model. As we move down the model, we gain access to additional lower-level features that certain workloads require.
Before moving on to layer 4 load balancers, if you deployed the NGINX example on your cluster, you should delete all of the objects before moving on. To easily remove the objects, you can execute the ngnix-ingress-remove.sh script in the chapter4/ingress directory. This script will delete the deployment, service, and ingress rule.
Layer 4 load balancers
Section titled “Layer 4 load balancers”Similar, to layer 7 load balancers, a layer 4 load balancer is also a traffic controller for a network, but with a number of differences compared to a layer 7 load balancer.
The layer 7 load balancer understands the content of incoming requests, making decisions based on specific information like web pages or data being requested. A layer 4 load balancer works at a lower level, looking at the basic information contained in the incoming network traffic, such as IP addresses and ports, without inspecting the actual data.
When you access a website or use an app, your device sends a request to the server with a unique IP address and a specific port number – also called a socket. The layer 4 load balancer observes this address and port to efficiently distribute incoming traffic across multiple servers. To help visualize how layer 4 load balancers work, think of it as a traffic cop that efficiently directs incoming cars to different lanes on a highway. The load balancer doesn’t know the exact destination or purpose of each car; it just looks at their license plate numbers and directs them to the appropriate lane to ensure smooth traffic flow.
In this way, the layer 4 load balancer ensures that the servers receive a fair share of incoming requests and that the network operates efficiently. It’s an essential tool to make sure that websites and applications can handle a large number of users without getting overwhelmed, helping to maintain a stable and reliable network.
There are lower-level networking operations in the process that are beyond the scope of this book. HAProxy has a good summary of the terminology and example configurations on its website at https://www.haproxy.com/fr/blog/loadbalancing-faq/.
In summary, a layer 4 load balancer is a network tool that distributes incoming traffic based on IP addresses and port numbers, allowing websites and applications to perform efficiently and deliver a seamless user experience.
Layer 4 load balancer options
Section titled “Layer 4 load balancer options”There are multiple options available to you if you want to configure a layer 4 load balancer for a Kubernetes cluster. Some of the options include the following:
- HAProxy
- NGINX Pro
- Seesaw
- F5 Networks
- MetalLB
Each option provides layer 4 load balancing, but for the purpose of this book, we will use MetalLB, which has become a popular choice for providing a layer 4 load balancer to a Kubernetes cluster.
Using MetalLB as a layer 4 load balancer
Section titled “Using MetalLB as a layer 4 load balancer”Remember that in Chapter 2, Deploying Kubernetes Using KinD, we had a diagram showing the flow of traffic between a workstation and the KinD nodes. Because KinD was running in a nested Docker container, a layer 4 load balancer would have had certain limitations when it came to networking connectivity. Without additional network configuration on the Docker host, you will not be able to target the services that use the LoadBalancer type outside of the Docker host itself. However, if you deploy MetalLB to a standard Kubernetes cluster running on a host, you will not be limited to accessing services outside of the host itself.
MetalLB is a free, easy-to-configure layer 4 load balancer. It includes powerful configuration options that give it the ability to run in a development lab or an enterprise cluster. Since it is so versatile, it has become a very popular choice for clusters requiring layer 4 load balancing.
We will focus on installing MetalLB in layer 2 mode. This is an easy installation and works for development or small Kubernetes clusters. MetalLB also offers the option to deploy using BGP mode, which allows you to establish peering partners to exchange networking routes. If you would like to read about MetalLB’s BGP mode, you can read about it on MetalLB’s site at https://metallb.universe.tf/concepts/bgp/.
Installing MetalLB
Section titled “Installing MetalLB”Before we deploy MetalLB to see it in action, we should start with a new cluster. While this isn’t required, it will limit any issues from any resources you may have been testing from prvious chapter. To delete the cluster and redeploy a fresh cluster, follow the steps below:
- Delete the cluster using the
kind deletecommand.kind delete cluster --name cluster01 - To redeploy a new cluster, change your directory to the
chapter2directory where you cloned the repo - Create a new cluster using the
create-cluster.shin the root of thechapter2directory - Once deployed, change your directory to the
chapter4/metallbdirectory
We have included a script called install-metallb.sh in the chapter4/metallb directory. The script will deploy MetalLB v0.13.10 using a pre-built configuration file called metallb-config.yaml. Once completed, the cluster will have the MetalLB components deployed, including the controller and the speakers.
The script, which you can look at, to understand what each step does by looking at the comments, execute the following steps to deploy MetalLB in your cluster:
- MetalLB is deployed into the cluster. The script will wait until the MetalLB controller is fully deployed.
- The script will find the IP range used on the Docker network. These will be used to create two different pools to use for LoadBalancer services.
- Using the values for the address pools, the script will inject the IP ranges into two resources -
metallb-pool.yamlandmetallb-pool-2.yaml. - The first pool is deployed using
kubectl applyand it also deploys thel2advertisementresource. - The script will show the pods from the MetalLB namespace to confirm they have been deployed.
- Finally, a NGINX web server pod will be deployed called
nginx-lband a LodBalancer service to provide access to the deployment using a MetallLB IP address.
MetalLB resources like address pools and the l2advertisement resource will be explained in the upcoming sections.
If you want to read about the available options when you deploy MetalLB, you can visit the installation page on the MetalLB site: https://metallb.universe.tf/installation/.
Now that MetalLB has been deployed to the cluster, let’s explain the MetalLB configuration file that configures how MetalLB will handle requests.
Understanding MetalLB’s custom resources
Section titled “Understanding MetalLB’s custom resources”MetalLB is configured using two custom resources that contain MetalLB’s configuration. We will be using MetalLB in layer 2 mode, and we will create two custom resources: the first is for the IP address range called IPAddressPool and the second configures what pools are advertised, known as an L2Advertisement resource.
The OSI model and the layers may be new to many readers – layer 2 refers to the layer of the OSI model; it plays a crucial role in enabling communication within a local network. It’s the layer where devices determine how to utilize the network infrastructure, like ethernet cables, and establish how to identify other devices. Layer 2 only deals with the local network segment; it doesn’t handle the task of directing traffic between different networks. That is the responsibility of layer 3 (the network layer) in the OSI model.
To put it simply, you can view layer 2 as the facilitator for devices within the same network to communicate. It achieves this by assigning MAC addresses (unique addresses) to devices and providing a method for sending and receiving data, which are organized into network packets. We have provided pre-configured resources in the chapter4/metallb directory called metallb-pool.yaml and l2advertisement.yaml. These files will configure MetalLB in layer 2 mode with an IP address range that is part of the Docker network, which will be advertised through the L2Advertisement resource.
To keep the configuration simple, we will use a small range from the Docker subnet in which KinD is running. If you were running MetalLB on a standard Kubernetes cluster, you could assign any range that is routable in your network, but we are limited in how KinD clusters deal with network traffic.
Let’s get into the details of how we created the custom resources. To begin, we need the IP range we want to advertise, and for our KinD cluster, that means we need to know what network range Docker is using. We can get the subnet by inspecting the KinD bridge network that KinD uses, using the docker network inspect command:
docker network inspect kind | grep -i subnetIn the output, you will see the assigned subnet, similar to the following:
"Subnet": "172.18.0.0/16"This is an entire Class B address range. We know that we will not use all of the IP addresses for running containers, so we will use a small range from the subnet in our MetalLB configuration.
Note: The term Class B is a reference to how IP addresses are divided into classes to define the range and structure of addresses for different network sizes. The primary classes are Class A, Class B, and Class C. Each class has a specific range of addresses and is used for different purposes.
These classes help organize and allocate IP addresses efficiently, ensuring that networks of different sizes have appropriate address spaces. For private networks, which are networks not directly connected to the internet, each class has a specific IP range reserved for this internal use:
- Class A Private Range:
10.0.0.0to10.255.255.255 - Class B Private Range:
172.16.0.0to172.31.255.255 - Class C Private Range:
192.168.0.0to192.168.255.255
Understanding subnets and class ranges is very important but it is beyond the scope of this book. If you are new to TCP/IP, you should consider reading about subnetting and class ranges.
If we look at our metallb-pool.yaml configuration file, we will see the configuration for IPAddressPool:
apiVersion: metallb.io/v1beta1kind: IPAddressPoolmetadata: name: pool-01 namespace: metallb-systemspec: addresses: - 172.18.200.100-172.18.200.125This manifest defines a new IPAddressPool called pool-01 in the metallb-system namespace, with an IP range set to 172.18.200.100 – 172.18.200.125.
IPAddressPool only defines the IP addresses that will be assigned to LoadBalancer services. To advertise the addresses, you need to associate the pools with an L2Advertisement resource. In the chapter4/metallb directory, we have a pre-defined L2Advertisement called l2advertisement.yaml, which is linked to the address pool we created, as shown here:
apiVersion: metallb.io/v1beta1kind: L2Advertisementmetadata: name: l2-all-pools namespace: metallb-systemWhen examining the preceding manifest, you might notice that there is minimal configuration involved. As we mentioned earlier, IPAddressPool needs to be associated with L2Advertisement, but in our current configuration, we haven’t specified any linking to the address pool we created. So, the question now is, how will our L2Advertisement announce or make use of the IPAddressPool we’ve created?
If you do not specify any pools in an L2Advertisement resource, each IPAddressPool that is created will be exposed. However, if you had a scenario where you only needed to advertise a few address pools, you could add the pool names to the L2Advertisement resource so that only the assigned pools would be advertised. For example, if we had three pools named pool1, pool2, and pool3 in a cluster, and we only wanted to advertise pool1 and pool3, we would create an L2Advertisement resource like the following example:
apiVersion: metallb.io/v1beta1kind: L2Advertisementmetadata: name: l2-all-pools namespace: metallb-systemspec: ipAddressPools: - pool1 - pool3With configuration out of the way, we will move on to explain how MetalLB’s components interact to assign IP addresses to services.
MetalLB components
Section titled “MetalLB components”Our deployment, which uses the standard manifest provided by the MetalLB project, will create a Deployment that will install the MetalLB controller and a DaemonSet that will deploy the second component to all nodes, called the speaker.
The Controller
Section titled “The Controller”The controller will receive announcements from the speaker on each worker node. These announcements show each service that has requested a LoadBalancer service, showing the assigned IP address that the controller assigned to the service:
{"caller":"main.go:49","event":"startUpdate","msg":"start of service update","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.437701161Z"}{"caller":"service.go:98","event":"ipAllocated","ip":"10.2.1.72","msg":"IP address assigned by controller","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.438079774Z"}{"caller":"main.go:96","event":"serviceUpdated","msg":"updated service object","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.467998702Z"}In the preceding example output, a Service called my-grafana-operator/grafana-operator-metrics has been deployed and MetalLB has assigned the IP address 10.2.1.72.
The Speaker
Section titled “The Speaker”The speaker component is what MetalLB uses to announce the LoadBalancer service’s IPs to the local network. This component runs on each node and ensures that the network configuration and the routers in your network are aware of the IP addresses assigned to the LoadBalancer services. This allows the LoadBalancer to receive traffic on its assigned IP address without needing additional network interface configurations on each node.
The speaker component in MetalLB is responsible for telling the local network how to access the services you’ve set up within your Kubernetes cluster. Think of it as the messenger that tells other devices on the network about the route they should take to send data meant for your applications.
It is primarily responsible for four tasks:
- Service detection: When a service is created in Kubernetes, the speaker component is always watching for
LoadBalancerservices. - IP address management: The speaker is in charge of managing IP addresses. It decides which IP addresses should be assigned to make the services accessible to external communication.
- Route announcements: After MetalLB’s speaker identifies the services that require external access and assigns the IP addresses, it communicates the route throughout your local network. It provides instructions to the network on how to connect to the services using the designated IP addresses.
- Load balancing: MetalLB performs network load balancing. If you have multiple pods, which all applications should, the speaker will distribute incoming network traffic among the pods, ensuring that the load is balanced for performance and reliability.
By default, it is deployed as a DaemonSet for redundancy – regardless of how many speakers are deployed, only one is active at any given time. The main speaker will announce all LoadBalancer service requests to the controller and if that speaker pod experiences a failure, another speaker instance will take over the announcements.
If we look at the speaker log from a node, we can see announcements, similar to the following example:
{"caller":"main.go:176","event":"startUpdate","msg":"start of service update","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.437231123Z"}{"caller":"main.go:189","event":"endUpdate","msg":"end of service update","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.437516541Z"}{"caller":"main.go:176","event":"startUpdate","msg":"start of service update","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.464140524Z"}{"caller":"main.go:246","event":"serviceAnnounced","ip":"10.2.1.72","msg":"service has IP, announcing","pool":"default","protocol":"layer2","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.464311087Z"}{"caller":"main.go:249","event":"endUpdate","msg":"end of service update","service":"my-grafana-operator/grafana-operator-metrics","ts":"2020-04-21T21:10:07.464470317Z"}The preceding announcement is for a Grafana component. In the announcement, you can see that the service has been assigned an IP address of 10.2.1.72 – this announcement will also go to the MetalLB controller, as we showed in the previous section.
Now that you have installed MetalLB and understand how the components create the services, let’s create our first LoadBalancer service on our KinD cluster.
Creating a LoadBalancer service
Section titled “Creating a LoadBalancer service”In the layer 7 load balancer section, we created a deployment running NGINX that we exposed by creating a service and an Ingress rule. At the end of the section, we deleted all of the resources to prepare for this test. If you followed the steps in the Ingress section and have not deleted the service and Ingress rule, please do so before creating the LoadBalancer service.
The MetalLB deployment script included an NGINX server with a LoadBalancer service. It will create an NGINX Deployment with a LoadBalancer service on port 80. The LoadBalancer service will be assigned an IP address from our defined pool, and since it’s the first service to use the address pool, it will likely be assigned 172.18.200.100.
You can test the service by using curl on the Docker host. Using the IP address that was assigned to the service, enter the following command:
curl 172.18.200.100You will receive the following output:

Figure 4.7: Curl output to the LoadBalancer service running NGINX
Adding MetalLB to a cluster allows you to expose applications that otherwise could not be exposed using a layer 7 balancer. Adding both layer 7 and layer 4 services to your clusters allows you to expose almost any application type you can think of, including databases.
In the next section, we will explain some of the advanced options that are available to create advanced IPAddressPool configurations.
Advanced pool configurations
Section titled “Advanced pool configurations”The MetalLB IPAddressPool resource offers a number of advanced options that are useful in different scenarios, including the ability to disable automatic assignments of addresses, use static IP addresses and multiple address pools, scope a pool to a certain namespace or service, and handle buggy networks.
Disabling automatic address assignments
Section titled “Disabling automatic address assignments”When a pool is created, it will automatically start to assign addresses to any service that requests a LoadBalancer type. While this is a common implementation, you may have special use cases where a pool should only assign an address if it is explicitly requested.
Assigning a static IP address to a service
Section titled “Assigning a static IP address to a service”When a service is assigned an IP address from the pool, it will keep the IP until the service is deleted and recreated. Depending on the number of LoadBalancer services being created, it is possible that the same IP address could be assigned when it is re-created, but there is no guarantee and we have to assume that the IP may change.
If we have an add-on like external-dns, which will be covered in the next chapter, you may not care that the IP address changes on a service since you would be able to use a name that is registered with the assigned IP address. In some scenarios, you may have little choice in deciding whether you can use the IP or name for a service and may experience issues if the address were to change during a redeployment.
As of the time of this writing, Kubernetes includes the ability to assign an IP address that a service will be assigned by adding spec.loadBalancerIP to the service resource, with the desired IP address. By using this option, you can “statically” assign the IP address to your service and if the service is deleted and redeployed, it will stay the same. This becomes useful in multiple scenarios, including the ability to add the known IP to other systems like Web Application Firewalls (WAFs) and firewall rules.
Starting in Kubernetes 1.24, the loadBalancerIP spec has been deprecated and while it will work in Kubernetes 1.27, the field may be removed in a future K8s release. Since the option will be removed at some point, it is suggested to use a solution that is included in the layer 4 load balancer you have deployed. In the case of MetalLB, they have added an annotation to assign an IP called metallb.universe.tf/loadBalancerIPs. Setting this field to the desired IP address will accomplish the same goal of using the deprecated spec.loadBalancerIP.
You may be thinking that assigning a static IP may come with some potential risks like conflicting IP assignments, which cause connectivity issues. Luckily, MetalLB has some features to mitigate these potential risks. If MetalLB is not the owner of the requested address or if the address is already being utilized by another service, the IP assignment will fail. If this failure occurs, MetalLB will generate a warning event, which can be viewed by running the kubectl describe service <service name> command.
The following manifest shows how to use both the native Kubernetes loadBalancerIP and MetalLB’s annotation to assign a static IP address to a service. The first example shows the deprecated spec.loadBalancerIP, assigning an IP address of 172.18.200.210 to the service:
apiVersion: v1kind: Servicemetadata: name: nginx-webspec: ports: - port: 80 targetPort: 8080 selector: app: nginx-web type: LoadBalancer loadBalancerIP: 172.18.200.210The following example shows how to set MetalLB’s annotation to assign the same IP address:
apiVersion: v1kind: Servicemetadata: name: nginx-web annotations: metallb.universe.tf/loadBalancerIPs: 172.18.200.210spec: ports: - port: 80 targetPort: 8080 selector: app: nginx-web type: LoadBalancerThe next section will discuss how to add additional address pools to your MetalLB configuration and how to use the new pools to assign an IP address to a service.
Using multiple address pools
Section titled “Using multiple address pools”In our original example, we created a single node pool for our cluster. It’s not uncommon to have a single address pool for a cluster, but in a more complex environment, you may need to add additional pools to direct traffic to a certain network, or you may need to simply add an additional pool due to simply running out of address in your original pool.
You can create as many address pools as you require in a cluster. We assigned a handful of addresses in our first pool, and now we need to add an additional pool to handle the number of workloads on the cluster. To create a new pool, we simply need to deploy a new IPAddressPool, as shown in the following:
apiVersion: metallb.io/v1beta1kind: IPAddressPoolmetadata: name: pool-02 namespace: metallb-systemspec: addresses: - 172.18.201.200-172.18.201.225The current release of MetalLB will require a restart of the MetalLB controller for the new address pool to be available.
Notice the name of this pool is pool-01, with a range of 172.18.201.200 – 172.18.201.225, whereas our original pool was pool-01 with a range of 172.18.200.200 – 172.18.200.225. Since we have deployed an L2Advertisement resource that exposes IPAddressPools, we do not need to create anything for the new pool to be announced.
Now that we have two active pools in our cluster, we can use a MetalLB annotation called metallb.universe.tf/address-pool in a service to assign the pool we want to pull an IP address from, as shown in the following example:
apiVersion: v1kind: Servicemetadata: name: nginx-web annotations: metallb.universe.tf/address-pool: pool-02spec: ports: - port: 80 targetPort: 8080 selector: app: nginx-web type: LoadBalancerIf we deploy this service manifest and then look at the services in the namespace, we will see that it has been assigned an IP address from the new pool, pool-02:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEnginx-lb-pool02 LoadBalancer 10.96.52.153 172.18.201.200 80:30661/TCP 3m8sOur cluster now offers LoadBalancer services the option of using either pool-01 or pool-02, based on the workload requirements.
You may be wondering how multiple address pools work if a service request does not explicitly define which pool to use. This is a great question, and we can control that by setting a value, known as a priority, to an address pool when created, defining the order of the pool that will assign the IP address.
Pools are a powerful feature, offering a highly configurable and flexible solution to provide the appropriate IP address pools to specific services.
MetalLB’s flexibility doesn’t stop with address pools. You may find that you have a requirement to create a pool that only a certain namespace or namespaces are allowed to use. This is called IP pool scoping and in the next section, we will discuss how to configure a scope to limit a pool’s usage based on a namespace.
When multiple IPAddressPools are available, MetalLB determines the availability of IPs by sorting the matching pools based on their priorities. The sorting starts with the highest priority (lowest priority number) and then proceeds to lower priority pools. If multiple IPAddressPools have the same priority, MetalLB selects one of them randomly. If a pool lacks a specific priority or is set to 0, it is considered the lowest priority and is used for assignment only when pools with defined priorities cannot be utilized.
In the following example, we have created a new pool called pool-03 and set a priority of 50 and another pool called pool-04 with a priority of 70:
apiVersion: metallb.io/v1beta1kind: IPAddressPoolmetadata: name: pool-03 namespace: metallb-systemspec: addresses: - 172.168.210.0/24 serviceAllocation: priority: 50apiVersion: metallb.io/v1beta1kind: IPAddressPoolmetadata: name: pool-04 namespace: metallb-systemspec: addresses: - 172.168.211.0/24 serviceAllocation: priority: 70If you create a service without selecting a pool, the request will match both of the pools shown previously. Since pool-03 has a lower priority number, it has a higher priority and will be used before pool-04 unless the pool is out of address, which will cause the request to use an IP from the pool-04 address pool.
As you can see, pools are powerful and flexible, providing a number of options to address different workload requirements. We have discussed how to select the pool using annotation and how different pools with priorities work. In the next section, we will discuss how we can link a pool to certain namespaces, limiting the workloads that can request an IP address from certain address pools.
IP pool scoping
Section titled “IP pool scoping”Multitenant clusters are common in enterprise environments and, by default, a MetalLB address pool is available to any deployed LoadBalancer service. While this may not be an issue for many organizations, you may need to limit a pool, or pools, to only certain namespaces to limit what workloads can use certain address pools.
To scope an address pool, we need to add some fields to our IPAddressPool resource. For our example, we want to deploy an address pool that has the entire Class C range available to only two namespaces, web and sales:
apiVersion: metallb.io/v1beta1kind: IPAddressPoolmetadata: name: ns-scoped-pool namespace: metallb-systemspec: addresses: - 172.168.205.0/24 serviceAllocation: priority: 50 namespaces: - web - salesWhen we deploy this resource, the only services that can request an address from the pool must exist in either the web or sales namespaces. If a request is made from any other namespace for ns-scoped-pool, it will be denied and an IP address in the 172.168.205.0 range will not be assigned to the service.
The last option we will discuss in the next section is known as handling buggy networks.
Handling buggy networks
Section titled “Handling buggy networks”MetalLB has a field that some networks may require to handle IP blocks ending in either .0 or .255. Older networking devices may flag the traffic as a possible Smurf attack, blocking the traffic. If you happen to run into this scenario, you will need to set the AvoidBuggyIPs field in the IPAddressPool resource to true.
At a high level, a Smurf attack sends a large number of network messages to special addresses that will reach all computers on the network. The traffic makes all computers think that the traffic is coming from a specific address, causing all of the computers to send a response to that specific machine. This traffic results in a denial-of-service attack, causing the machine to go offline and disrupting any services that were running.
To avoid this issue, setting the AvoidBuggyIPs field will prevent the .0 and .255 addresses from being used. An example manifest is shown here:
apiVersion: metallb.io/v1beta1kind: IPAddressPoolmetadata: name: buggy-example-pool namespace: metallb-systemspec: addresses: - 172.168.205.0/24 avoidBuggyIPs: trueAdding MetalLB as a layer 4 load balancer to your cluster allows you to migrate applications that may not work with simple layer 7 traffic.
As more applications are migrated or refactored for containers, you will run into many applications that require multiple protocols for a single service. In the next section, we will explain some scenarios where having multiple protocols for a single service is required.
Using multiple protocols
Section titled “Using multiple protocols”Earlier versions of Kubernetes did not allow services to assign multiple protocols to a LoadBalancer service. If you attempted to assign both TCP and UDP to a single service, you would receive an error that multiple protocols were not supported and the resource would fail to deploy.
Although MetalLB still provides support for this, there’s little incentive to utilize those annotations since newer versions of Kubernetes introduced an alpha feature gate called MixedProtocolLBService in version 1.20. It has since graduated to general availability starting in Kubernetes version 1.26, making it a base feature that enables the use of different protocols for LoadBalancer-type services when multiple ports are defined.
Using a CoreDNS example, we need to expose our CoreDNS to the outside world. We will explain a use case in the next chapter where we need to expose a CoreDNS instance to the outside world using both TCP and UDP.
Since DNS servers use both TCP and UDP port 53 for certain operations, we need to create a service that will expose our service as a LoadBalancer type, listening to both TCP and UDP port 53. Using the following example, we create a new service that has both TCP and UDP defined:
apiVersion: v1kind: Servicemetadata: name: coredns-ext namespace: kube-systemspec: selector: k8s-app: kube-dns ports: - name: dns-tcp port: 53 protocol: TCP targetPort: 53 - name: dns-udp port: 53 protocol: UDP targetPort: 53 type: LoadBalancerIf we deployed the manifest and then looked at the services in the kube-system namespace, we would see that the service was created successfully and that both port 53 on TCP and UDP have been exposed:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEcoredns-ext LoadBalancer 10.96.192.4 172.18.200.101 53:31889/TCP,53:31889/UDP 6sYou will see that the new service was created, coredns-ext, assigned the IP address of 172.18.200.101, and exposed on TCP and UDP port 53. This will now allow the service to accept connections on both protocols using port 53.
One issue that many load balancers have is that they do not provide name resolution for the service IPs. Users prefer to target an easy-to-remember name rather than random IP addresses when they want to access a service. Kubernetes does not provide the ability to create externally accessible names for services, but there is an incubator project to enable this feature. In Chapter 5, we will explain how we can provide external name resolution for Kubernetes services.
In the final section of the chapter, we will discuss how to secure our workloads using network policies.
Introducing Network Policies
Section titled “Introducing Network Policies”Security is something that all Kubernetes users should think about from day 1. By default, every pod in a cluster can communicate with any other pod in the cluster, even other namespaces that you may not own. While this is a basic Kubernetes concept, it’s not ideal for most enterprises, and when using multi-tenant clusters, it becomes a big security concern. We need to increase the security and isolation of workloads, which can be a very complex task, and this is where network policies come in.
NetworkPolicies provide users the ability to control their network traffic for both egress and ingress using a defined set of rules between pods, namespaces, and external endpoints. Think of a network policy as a firewall for your clusters, providing fine-grained access controls based on various parameters. Using network policies, you can control which pods are allowed to communicate with other pods, restrict traffic to specific protocols or ports, and enforce encryption and authentication requirements.
Like most Kubernetes objects that we have discussed, network policies allow control based on labels and selectors. By matching the labels specified in a network policy, Kubernetes can determine which pods and namespaces should be allowed or denied network access.
Network policies are an optional feature in Kubernetes, and the CNI being used in the cluster must support them to be used. On the KinD cluster we created, we deployed Calico, which does support network policies, however, not all network plugins support network policies out of the box, so it’s important to plan out your requirements before deploying a cluster.
In this section, we will explain the options provided by network policies to enhance the overall security of your applications and cluster.
Network policy object overview
Section titled “Network policy object overview”Network policies provide a number of options to control both ingress and egress traffic. They can be granular to only allow certain pods, namespaces, or even IP addresses to control the network traffic.
There are four parts to a network policy. Each part is described in the following table.
| Spec | Description |
|---|---|
podSelector | This limits the scope of workloads that a policy is applied to, using a label selector. If no selector is provided, the policy will affect every pod in the namespace. |
policyTypes | This defines the policy rules. The valid types are ingress and egress. |
ingress | (optional) This defines the rules to follow for ingress traffic. If there are no rules defined, it will match all incoming traffic. |
egress | (optional) This defines the rules to follow for egress traffic. If there are no rules defined, it will match all outgoing traffic. |
Table.4.6: Parts of a network policy
The ingress and egress portions of the policy are optional. If you do not want to block any egress traffic, simply omit the egress spec. If a spec is not defined, all traffic will be allowed.
The podSelector
Section titled “The podSelector”The podSelector field is used to tell you what workloads a network policy will affect. If you wanted the policy to only affect a certain deployment, you would define a label that would match a label in the deployment. The label selectors are not limited to a single entry; you can add multiple label selectors to a network policy, but all selectors must match for the policy to be applied to the pod. If you want the policy to be applied to all pods, leave the podSelector blank; it will apply the policy to every pod in the namespace.
In the following example, we have defined that the policy will only be applied to pods that match the label app=frontend:
spec: podSelector: matchLabels: app: frontendThe next field is the type of policy, which is where you define a policy for ingress and egress.
The policyTypes
Section titled “The policyTypes”The policyType field specifies the type of policy being defined, determining the scope and behavior of the NetworkPolicy. There are two available options for policyType:
| policyType | Description |
|---|---|
ingress | ingress controls incoming network traffic to pods. It defines the rules that control the sources that are allowed to access the pods matching the podSelector specified in the NetworkPolicy. Traffic can be allowed from specific IP CIDR ranges, namespaces, or from other pods within the cluster. |
egress | egress controls outgoing network traffic from pods. It defines rules that control the destinations that pods are allowed to communicate with. Egress traffic can be restricted by specific IP CIDR ranges, namespaces, or other pods within the cluster. |
Table 4.7: The policy types
Policies can contain ingress, egress, or both options. If one policy type is not included, it will not affect that traffic type. For example, if you only include an ingress policyType, all egress traffic will be allowed at any location on the network.
As we mentioned, when you create a rule for either ingress or egress traffic, you can provide no label, a single label, or multiple labels that must match for the policy to take effect. The following example shows an ingress block that has three labels; in order for the policy to affect a workload, all three declared fields must match:
ingress: - from: - ipBlock: cidr: 192.168.0.0/16 - namespaceSelector: matchLabels: app: backend - podSelector: matchLabels: app: databaseIn the preceding example, any incoming traffic needs to be coming from a workload that has an IP address in the 192.168.0.0 subnet, in the namespace that has a label of app=backend, and finally, the requesting pod must have a label of app=database.
While the example shows options for ingress traffic, the same options are available for egress traffic.
Now that we have covered the options that are available in a network policy, let’s move on to creating a full policy using a real-world example.
Creating a Network Policy
Section titled “Creating a Network Policy”We have included a network policy script in the chapter4/netpol directory in the book’s GitHub repository called netpol.sh. When you execute the script, it will create a namespace called sales, with a few pods with labels and a network policy. The policy that is created will be the basis for the policy we will go over in this section.
When you create a network policy, you need to have an understanding of the desired network restrictions. The person who is most aware of the application traffic flow is best suited to help create a working policy. You need to consider the pods or namespaces that should be able to communicate, which protocols and ports should be allowed, and whether you need any additional security like encryption or authentication.
Like other Kubernetes objects, you need to create a manifest using the NetworkPolicy object and provide metadata like the name of the policy and the namespace that it will be deployed in.
Let’s use an example where you have a backend pod running PostgreSQL in the same namespace as a web server. We know that the only pod that needs to talk to the database server is the web server itself and no other communication should be allowed to the database.
To begin, we need to create our manifest, and it will start out by declaring the API, kind, policy name, and namespace:
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: backend-netpol namespace: salesThe next step is to add the pod selector to specify the pods that will be affected by the policy. This is done by creating a podSelector section where you define selectors based on any pods with matching labels. For our example, we want our policy to apply to pods that are part of the backend database application. The pods for the application have all been labeled with app=backend-db:
spec: podSelector: matchLabels: app.kubernetes.io/name: postgresqlNow that we have declared what pods to match, we need to define the ingress and egress rules, which are defined with the spec.ingress or spec.egress section of the policy. For each rule type, you can set the allowed protocols and ports for the application, and control from where an external request is allowed to access the port. To build on our example, we want to add an ingress rule that will allow port 5432 from pods with a label of app=backend:
spec: podSelector: matchLabels: app: frontend ingress: - from: - podSelector: matchLabels: app: frontend ports: - protocol: TCP port: 5432As the last step, we will define our policy type. Since we are only concerned with incoming traffic to the PostgreSQL pod, we only need to declare one type, ingress:
policyTypes: - IngressOnce this policy is deployed, the pods running in the sales namespace that have an app=backend-db label will only receive traffic from pods that have a label of app=frontend on TCP port 5432. Any request other than port 5432 from a frontend pod will be denied. This policy makes our PostgreSQL deployment very secure since any incoming traffic is tightly locked down to a specific workload and TCP port.
When we execute the script from the repository, it will deploy PostgreSQL to the cluster and add a label to the deployment. We are going to use the label to tie the network policy to the PostgreSQL pod. To test the connectivity, and the network policy, we will run a netshoot pod and use telnet to test connecting to the pod on port 5432.
We need to know the IP address to test the network connection. To get the IP for the database server, we just need to list the pods in the namespace using the -o wide option, to list the IP of the pods. Now that PostgreSQL is running, we will simulate a connection by running a netshoot pod with a label that doesn’t match app: frontend, which will result in a failed connection. See the following:
kubectl get pods -n sales -o wideNAME READY STATUS RESTARTS AGE IPdb-postgresql-0 0/1 Running 0 45s 10.240.189.141kubectl run tmp-shell --rm -i --tty --image nicolaka/netshoot --labels app=wronglabel -n salestmp-shell ~ telnet 10.240.189.141:5432The connection will eventually time out since the incoming request has a pod labeled app=wronglabel. The policy will look at the labels from the incoming request and if none of them match, it will deny the connection.
Finally, let’s see whether we created our policy correctly. We will run netshoot again, but this time with the correct label, we will see that the connection succeeds:
kubectl run tmp-shell --rm -i --tty --image nicolaka/netshoot --labels app=frontend -n salestmp-shell ~ telnet 10.240.189.141:5432Connected to 10.240.189.141:5432Notice the line, which says Connected to 10.240.189.141:5432. This shows that the PostgreSQL pod accepted the incoming request from the netshoot pod since the label for the pod matches the network policy, which is looking for a label of app=frontend.
So, why does the network policy allow only port 5432? We didn’t set any options to deny traffic; we defined only the allowed traffic. Network policies follow a default deny-all for any policy that isn’t defined. In our example, we only defined port 5432, so any request that is not on port 5432 will be denied. Having a deny-all for any undefined communication helps to secure your workload by avoiding any unintended access.
If you wanted to create a deny-all network policy, you would just need to create a new policy that has ingress and egress added, with no other values. An example is shown as follows:
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: deny-all namespace: salesspec: podSelector: {} policyTypes: - Ingress - EgressIn this example, we have set podSelector to {}, which means the policy will apply to all pods in the namespace. In the spec.ingress and spec.egress options, we haven’t set any values, and since the default behavior is to deny any communication that doesn’t have a rule, this rule will deny all ingress and egress traffic.
Tools to create network policies
Section titled “Tools to create network policies”Network policies can be difficult to create manually. It can be challenging to know what ports you need to open, especially if you aren’t the application owner.
In Chapter 13, KubeArmor Securing Your Runtime, we will discuss a tool called KubeArmor, which is a CNCF project that was donated by a company called AccuKnox. KubeArmor was primarily a tool to secure container runtimes, but recently they added the ability to watch the network traffic flow between pods. By watching the traffic, they know the “normal behavior” of the network connections for the pod and it creates a ConfigMap for each observed network policy in the namespace.
We will go into details in Chapter 13; for now, we just wanted to let you know that there are tools to help you create network policies.
In the next chapter, we’ll learn how to use CoreDNS to create service name entries in DNS using an incubator project called external-dns. We will also introduce an exciting CNCF sandbox project called K8GB that provides a cluster with Kubernetes’ native global load-balancing features.
Summary
Section titled “Summary”In this chapter, you learned how to expose your workloads in Kubernetes to other cluster resources and external traffic.
The first part of the chapter went over services and the multiple types that can be assigned. The three major service types are ClusterIP, NodePort, and LoadBalancer. Remember that the selection of the type of service will configure how your application is exposed.
In the second part, we introduced two load balancer types, layer 4 and layer 7, each having a unique functionality for exposing workloads. You will often use a ClusterIP service along with an ingress controller to provide access to services that use layer 7. Some applications may require additional communication, not provided by a layer 7 load balancer. These applications may require a layer 4 load balancer to expose their services externally. In the load balancing section, we demonstrated the installation and use of MetalLB, a popular, open-source, layer 4 load balancer.
We closed out the chapter by discussing how to secure both ingress and egress network traffic. Since Kubernetes, by default, allows communication between all pods in a cluster, most enterprise environments need a way to secure the communication between workloads to only the required traffic for the application. Network policies are a powerful tool to secure a cluster and limit the traffic flow for both incoming and outgoing traffic.
You may still have some questions about exposing workloads, such as the following: how can we handle DNS entries for services that use a LoadBalancer type? Or, maybe, how do we make a deployment highly available between two clusters?
In the next chapter, we will expand on using the tools that are useful for exposing your workloads, like name resolution and global load balancing.
Questions
Section titled “Questions”- How does a service know what pods should be used as endpoints for the service?
- By the service port 2. By the namespace 3. By the author 4. By the selector label
Answer: d
- What
kubectlcommand helps you troubleshoot services that may not be working properly?kubectl get services <service name>2.kubectl get ep <service name>3.kubectl get pods <service name>4.kubectl get servers <service name>
Answer: b
- All Kubernetes distributions include support for services that use the
LoadBalancertype.- True 2. False
Answer: b
- Which load balancer type supports all TCP/UDP ports and accepts traffic regardless of the packet’s contents?
Answer: d