Diving Deep Into Kubernetes Networking 1667510323
Diving Deep Into Kubernetes Networking 1667510323
Diving Deep
into Kubernetes
Networking
2022
Contents
Introduction 3 Networking with Cilium 43
Goals for this book 3 Architecture 43
How this book is organized 3 Install Cilium with Kubernetes 45
An Introduction to networking with Docker 4 Networking with Kube-vip 49
Docker networking types 4 Architecture 49
Container-to-Container Communication 10 Install Kube-vip with Kubernetes 50
Container Communication between hosts 12 Networking with MetalLB 56
Interlude: Netfilter and Iptables rules 13 Architecture 56
The Filter Table 13 Install MetalLB with Kubernetes 56
The NAT Table 13 Load Balancers and Ingress Controllers 59
The Mangle Table 13 The benefits of Load Balancers 59
Raw Table 13 Networking with Flannel and Calico (Canal) 63
Security Table 13 Load Balancing in Kubernetes 63
An Introduction to Kubernetes Networking 15 Conclusion 70
POD Networking 16
Service Mesh 19
Network Policy 20
Flannel Backends 29
Architecture 31
Using IP-in-IP 36
Architecture 37
The reader is expected to have a basic understanding of containers, Kubernetes, and operating system
fundamentals.
This eBook covers Kubernetes networking concepts, but we do not intend for it to be a detailed explanation of
Kubernetes in its entirety. For more information on Kubernetes, we recommend reading the eBook, Kubernetes
Management for Dummies as well as the Kubernetes documentation.
The network providers are pluggable using drivers. We connect a Docker container to a particular network by using
the --net switch when launching it.
The following command launches a container from the busybox image and joins it to the host network. This
container prints its IP address and then exits.
Docker offers five network types, each with a different capacity for communication with other network entities.
a) Host Networking: The container shares the same IP address and network namespace as that of the host.
Services running inside of this container have the same network capabilities as services running directly on the
host.
b) Bridge Networking: The container runs in a private network internal to the host. Communication is open to other
containers in the same network. Communication with services outside of the host goes through network address
translation (NAT) before exiting the host. (This is the default mode of networking when the --net option isn’t
specified)
c) Custom bridge network: This is the same as Bridge Networking but uses a bridge explicitly created for this (and
other) containers. An example of how to use this would be a container that runs on an exclusive “database”
bridge network. Another container can have an interface on the default bridge and the database bridge,
enabling it to communicate with both networks.
d) Container-defined Networking: A container can share the address and network configuration of another
container. This type enables process isolation between containers, where each container runs one service but
where services can still communicate with one another on the localhost address.
If you run the command ip addr on a host (or ifconfig -a if your host doesn’t have the ip command available),
you will see information about the network interfaces.
If you run the same command from a container using host networking, you will see the same information.
To demonstrate using the default bridge, run the following command on a host with Docker installed. Since we are
not specifying the network - the container will connect to the default bridge when it launches.
Run the ip addr and ip route commands inside of the container. You will see the IP address of the container with
the eth0 interface:
In another terminal connected to the host, run the ip addr command. You will see the corresponding interface
created for the container. In the image below it is named veth5dd2b68@if9. Yours will be different.
By default, the Docker container can send traffic to any destination. The Docker daemon creates a rule within
Netfilter that modifies outbound packets and changes the source address to be the address of the host itself. The
Netfilter configuration allows inbound traffic via the rules that Docker creates when initially publishing the container’s
ports.
The output included below shows the Netfilter rules created by Docker when it publishes a container’s ports.
—
All containers in a custom bridge can communicate with the ports of other containers on that bridge. This means
that you do not need to publish the ports explicitly. It also ensures that the communication between them is
secure. Imagine an application in which a backend container and a database container need to communicate
and where we also want to make sure that no external entity can talk to the database. We do this with a custom
bridge network in which only the database container and the backend containers reside. You can explicitly
expose the backend API to the rest of the world using port publishing.
— The same is true with environment variables - environment variables in a bridge network are shared by all
containers on that bridge.
The following commands launch two containers that share the same network namespace and thus share the same
IP address. Services running on one container can talk to services running on the other via the localhost address.
No Networking
This mode is useful when the container does not need to communicate with other containers or
with the outside world. It is not assigned an IP address, and it cannot publish any ports.
Container Container
Packet
1 4
2 3
vethxxx vethyyy
docker0 bridge
ip tables
eth0
In the above diagram, two containers running on the same host connect via the docker0 bridge. If 172.17.0.6 (on
the left-hand side) wants to send a request to 172.17.0.7 (the one on the right-hand side), the packets move as
follows:
1. A packet leaves the container via eth0 and lands on the corresponding vethxxx interface.
2. The vethxxx interface connects to the vethyyy interface via the docker0 bridge.
4. The packet moves to the eth0 interface within the destination container.
We can see this in action by using ping and tcpdump. Create two containers and inspect their network configuration
with ip addr and ip route. The default route for each container is via the eth0 interface.
Cross-host networking usually uses an overlay network, which builds a mesh between hosts and employs a large
block of IP addresses within that mesh. The network driver tracks which addresses are on which host and shuttles
packets between the hosts as necessary for inter-container communication.
Overlay networks can be encrypted or unencrypted. Unencrypted networks are acceptable for environments in
which all of the hosts are within the same LAN, but because overlay networks enable communication between hosts
across the Internet, consider the security requirements when choosing a network driver. If the packets traverse a
network that you don’t control, encryption is a better choice.
The overlay network functionality built into Docker is called Swarm. When you connect a host to a swarm, the Docker
engine on each host handles communication and routing between the hosts.
Other overlay networks exist, such as IPVLAN, VxLAN, and MACVLAN. More solutions are available for Kubernetes.
For more information on pure-Docker networking implementations for cross-host networking (including Swarm
mode and libnetwork), please refer to the documentation available at the Docker website, https://docs.docker.com/.
Netfilter manages the rules that define network communication for the Linux kernel. These rules permit, deny, route,
modify, and forward packets. It organizes these rules into tables according to their purpose.
Raw Table
This table marks packets to bypass the iptables stateful connection tracking.
Security Table
This table sets the SELinux security context marks on packets. Setting the marks affects how SELinux (or systems that
can interpret SELinux security contexts) handle the packets. The rules in this table set marks on a per-packet or per-
connection basis.
Netfilter organizes the rules in a table into chains. Chains are the means by which Netfilter hooks in the kernel
intercept packets as they move through processing. Packets flow through one or more chains and exit when they
match a rule.
The action that a rule takes is called a target, and represents the decision to accept, drop, or forward the packet.
The system comes with five default chains that match different phases of a packet’s journey through processing:
PREROUTING, INPUT, FORWARD, OUTPUT, and POSTROUTING. Users and programs may create additional chains and
inject rules into the system chains to forward packets to a custom chain for continued processing. This architecture
allows the Netfilter configuration to follow a logical structure, with chains representing groups of related rules.
Docker creates several chains, and it is the actions of these chains that handle communication between containers,
the host, and the outside world.
Pods
The smallest unit of deployment in a Kubernetes cluster is the Pod, and all of the constructs related to scheduling
and orchestration assist in the deployment and management of Pods.
In the simplest definition, a Pod encapsulates one or more containers. Containers in the same Pod always run on the
same host. They share resources such as the network namespace and storage.
Each Pod has a routable IP address assigned to it, not to the containers running within it. Having a shared network
space for all containers means that the containers inside can communicate with one another over the localhost
address, a feature not present in traditional Docker networking.
The most common use of a Pod is to run a single container. Situations where different processes work on the same
shared resource, such as content in a storage volume, benefit from having multiple containers in a single Pod. Some
projects inject containers into running Pods to deliver a service. An example of this is the Istio service mesh, which
uses this injected container as a proxy for all communication.
Because a Pod is the basic unit of deployment, we can map it to a single instance of an application. For example, a
three-tier application that runs a user interface (UI), a backend, and a database would model the deployment of the
application on Kubernetes with three Pods. If one tier of the application needed to scale, the number of Pods in that
tier could scale accordingly.
Workloads
Production applications with users run more than one instance of the application. This enables fault tolerance, where
if one instance goes down, another handles the traffic so that users don’t experience a disruption to the service.
In a traditional model that doesn’t use Kubernetes, these types of deployments require that an external person or
software monitors the application and acts accordingly.
Kubernetes recognizes that an application might have unique requirements. Does it need to run on every host?
Does it need to handle state to avoid data corruption? Can all of its pieces run anywhere, or do they need special
scheduling consideration? To accommodate those situations where a default structure won’t give the best results,
Kubernetes provides abstractions for different workload types.
Deployment
A Deployment manages a ReplicaSet. Although it’s possible to launch a ReplicaSet directly or to use a
ReplicationController, the use of a Deployment gives more control over the rollout strategies of the Pods that the
ReplicaSet controller manages. By defining the desired states of Pods through a Deployment, users can perform
updates to the image running within the containers and maintain the ability to perform rollbacks.
DaemonSet
A DaemonSet runs one copy of the Pod on each node in the Kubernetes cluster. This workload model provides the
flexibility to run daemon processes such as log management, monitoring, storage providers, or network providers
that handle Pod networking for the cluster.
StatefulSet
A StatefulSet controller ensures that the Pods it manages have durable storage and persistent identity. StatefulSets
are appropriate for situations where Pods have a similar definition but need a unique identity, ordered deployment
and scaling, and storage that persists across Pocd rescheduling.
Pod Networking
The Pod is the smallest unit in Kubernetes, so it is essential to first understand Kubernetes networking in the context
of communication between Pods. Because a Pod can hold more than one container, we can start with a look at
how communication happens between containers in a Pod. Although Kubernetes can use Docker for the underlying
container runtime, its approach to networking differs slightly and imposes some basic principles:
— Any Pod can communicate with any other Pod without the use of network address translation (NAT). To facilitate
this, Kubernetes assigns each Pod an IP address that is routable within the cluster.
These principles give a unique and first-class identity to every Pod in the cluster. Because of this, the networking
model is more straightforward and does not need to include port mapping for the running container workloads. By
keeping the model simple, migrations into a Kubernetes cluster require fewer changes to the container and how it
communicates.
The pause container was initially designed to act as the init process within a PID namespace shared by all
containers in the Pod. It performed the function of reaping zombie processes when a container died. PID namespace
sharing is now disabled by default, so unless it has been explicitly enabled in the kubelet, all containers run their
process as PID 1.
If we launch a Pod running Nginx, we can inspect the Docker container running within the Pod.
When we do so, we see that the container does not have the network settings provided to it. The pause container
which runs as part of the Pod is the one which gives the networking constructs to the Pod.
Note: Run the commands below on the host where the nginx Pod is scheduled.
Inter-Pod Communication
Because it assigns routable IP addresses to each Pod, and because it requires that all resources see the address of a
Pod the same way, Kubernetes assumes that all Pods communicate with one another via their assigned addresses.
Doing so removes the need for an external service discovery mechanism.
Kubernetes Service
Pods are ephemeral. The services that they provide may be critical, but because Kubernetes can terminate Pods at
any time, they are unreliable endpoints for direct communication. For example, the number of Pods in a ReplicaSet
might change as the Deployment scales it up or down to accommodate changes in load on the application, and it
is unrealistic to expect every client to track these changes while communicating with the Pods. Instead, Kubernetes
offers the Service resource, which provides a stable IP address and balances traffic across all of the Pods behind it.
This abstraction brings stability and a reliable mechanism for communication between microservices.
Services which sit in front of Pods use a selector and labels to find the Pods they manage. All Pods with a label that
matches the selector receive traffic through the Service. Like a traditional load balancer, the service can expose the
Pod functionality at any port, irrespective of the port in use by the Pods themselves.
Kube-proxy
The kube-proxy daemon that runs on all nodes of the cluster allows the Service to map traffic from one port to
another.
This component configures the Netfilter rules on all of the nodes according to the Service’s definition in the API
server. From Kubernetes 1.9 onward it uses the netlink interface to create IPVS rules. These rules direct traffic to the
appropriate Pod.
ClusterIP
This type of Service is the default and exists on an IP that is only visible within the cluster. It enables cluster resources
to reach one another via a known address while maintaining the security boundaries of the cluster itself. For
example, a database used by a backend application does not need to be visible outside of the cluster, so using a
service of type ClusterIP is appropriate. The backend application would expose an API for interacting with records in
the database, and a frontend application or remote clients would consume that API.
NodePort
A Service of type NodePort exposes the same port on every node of the cluster. The range of available ports is
a cluster-level configuration item, and the Service can either choose one of the ports at random or have one
designated in its configuration. This type of Service automatically creates a ClusterIP Service as its target, and the
ClusterIP Service routes traffic to the Pods.
LoadBalancer
When working with a cloud provider for whom support exists within Kubernetes, a Service of type LoadBalancer
creates a load balancer in that provider’s infrastructure. The exact details of how this happens differ between
providers, but all create the load balancer asynchronously and configure it to proxy the request to the corresponding
Pods via NodePort and ClusterIP Services that it also creates.
In a later section, we explore Ingress Controllers and how to use them to deliver a load balancing solution for a
cluster.
DNS
As we stated above, Pods are ephemeral, and because of this, their IP addresses are not reliable endpoints for
communication. Although Services solve this by providing a stable address in front of a group of Pods, consumers
of the Service still want to avoid using an IP address. Kubernetes solves this by using DNS for service discovery.
The default internal domain name for a cluster is cluster.local. When you create a Service, it assembles a
subdomain of namespace.svc.cluster.local (where namespace is the namespace in which the service is
running) and sets its name as the hostname. For example, if the service was named nginx and ran in the default
namespace, consumers of the service would be able to reach it as nginx.default.svc.cluster.local. If the
service’s IP changes, the hostname remains the same. There is no interruption of service.
The default DNS provider for Kubernetes is KubeDNS, but it’s a pluggable component. Beginning with Kubernetes 1.11
CoreDNS is available as an alternative. In addition to providing the same basic DNS functionality within the cluster,
CoreDNS supports a wide range of plugins to activate additional functionality.
Service Mesh
Modern applications are typically composed of distributed collections of microservices, each of which performs a
discrete business function. As a network of microservices changes and grows, the interactions between them can
become increasingly difficult to manage and understand. In such situations, it is useful to have a service mesh as a
dedicated infrastructure layer to control service-to-service communication over a network.
A service mesh controls the delivery of service requests in an application so that separate parts of an application
can communicate with each other. Service meshes can make service-to-service communication fast, reliable and
secure.
— Traffic Management such as ingress and egress routing, circuit breaking, and mirroring.
— Security with resources to authenticate and authorize traffic and users, including mTLS.
— Observability of logs, metrics, and distributed traffic flows.
— Secure service-to-service communication in a cluster with TLS encryption, identity-based authentication and
authorization
— Automatic load balancing for HTTP, gRPC, WebSocket, and TCP traffic
— Granular control of traffic behavior with routing rules, retries, failovers, and fault injection
— A pluggable policy layer and configuration API supporting access controls, rate limits and quotas
— Automatic metrics, logs, and traces for all traffic within a cluster, including cluster ingress and egress
Functionally, Istio has two components: the data plane and the control plane. The data plane provides communication
between services. Istio uses a proxy to intercept all your network traffic, allowing a broad set of application-aware
features based on configuration you set. An Envoy proxy is deployed along with each service that you start in your
cluster, or runs alongside services running on VMs. This enables Istio to understand the traffic being sent and make
decisions based on what type of traffic it is, and which services are communicating. The Istio control plane takes your
desired configuration, and its view of the services, and dynamically programs the proxy servers, updating them as the
rules or the environment changes.
Network Policy
In an enterprise deployment of Kubernetes the cluster often supports multiple projects with different goals. Each of
these projects has different workloads, and each of these might require a different security policy.
Pods, by default, do not filter incoming traffic. There are no firewall rules for inter-Pod communication. Instead, this
responsibility falls to the NetworkPolicy resource, which uses a specification to define the network rules applied to a
set of Pods.
The network policies are defined in Kubernetes, but the CNI plugins that support network policy
implementation do the actual configuration and processing. In a later section, we look at CNI
plugins and how they work.
The image below shows a standard three-tier application with a UI, a backend service, and a database, all deployed
within a Kubernetes cluster.
backend pod
backend pod
Requests to the application arrive at the web Pods, which then initiate a request to the backend Pods for data.
The backend Pods process the request and perform CRUD operations against the database Pods.
If the cluster is not using a network policy, any Pod can talk to any other Pod. Nothing prevents the web Pods
from communicating directly with the database Pods. If the security requirements of the cluster dictate a
need for clear separation between tiers, a network policy enforces it.
The policy defined below states that the database Pods can only receive traffic from the Pods with the labels
app=myapp and role=backend. It also defines that the backend Pods can only receive traffic from Pods with
the labels app=myapp and role=web.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: db-access-ingress
spec:
podSelector:
matchLabels:
app: myapp
role: db
ingress:
- from:
- podSelector:
matchLabels:
app: myapp
role: backend
With this network policy in place, Kubernetes blocks communication between the web and database tiers.
backend pod
backend pod
podSelector
This field tells Kubernetes how to find the Pods to which this policy applies. Multiple network policies can select the
same set of Pods, and the ingress rules are applied sequentially. The field is not optional, but if the manifest defines
a key with no value, it applies to all Pods in the namespace.
policyTypes
This field defines the direction of network traffic to which the rules apply. If missing, Kubernetes interprets the rules
and only applies them to ingress traffic unless egress rules also appear in the rules list. This default interpretation
simplifies the manifest’s definition by having it adapt to the rules defined later.
Because Kubernetes always defines an ingress policy if this field is unset, a network policy for egress-only rules must
explicitly define the policyType of Egress.
egress
Rules defined under this field apply to egress traffic from the selected egress:
- to:
Pods to destinations defined in the rule. Destinations can be an IP block
- ipBlock:
(ipBlock), one or more Pods (podSelector), one or more namespaces cidr: 10.0.0.0/24
(namespaceSelector), or a combination of both podSelector and ports:
nameSpaceSelector. - protocol: TCP
port: 5978
The following rule permits traffic from the Pods to any address in
10.0.0.0/24 and only on TCP port 5978:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-egress-denyall
spec:
podSelector:
matchLabels:
app: myapp
role: backend
policyTypes:
- Egress
egress:
- ports:
- port: 53
protocol: UDP
- port: 53
protocol: TCP
Egress rules work best to limit a resource’s communication to the other resources on which it relies. If those resources
are in a specific block of IP addresses, use the ipBlock selector to target them, specifying the appropriate ports:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-egress-denyall
spec:
podSelector:
matchLabels:
app: myapp
role: backend
policyTypes:
- Egress
egress:
- ports:
- port: 53
protocol: UDP
- port: 53
protocol: TCP
- to:
- ipBlock:
cidr: 10.0.0.0/24
ports:
- protocol: TCP
port: 3306
(Note the subtle distinction in how the rules are listed. Because namespaceSelector is a separate item in the list,
it matches with an or value. Had namespaceSelector been listed as an additional key in the first list item, it would
permit traffic that came from the specified ipBlock and was also from the namespace myproject.)
ingress:
- from:
- ipBlock:
cidr: 172.17.0.0/16
except:
- 172.17.1.0/24
- namespaceSelector:
matchLabels:
project: myproject
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
The next policy permits access to the Pods labeled app=myapp and role=web from all sources, external or internal.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: web-allow-all-access
spec:
podSelector:
matchLabels:
app: myapp
role: web
ingress:
- from: []
Consider, however, that this allows traffic to any port on those Pods. Even if no other ports are listening, the principle
of least privilege states that we only want to expose what we need to expose for the services to work. The following
modifications to the NetworkPolicy take this rule into account by only allowing inbound traffic to the ports where our
Service is running.
Apart from opening incoming traffic on certain ports, you can also enable all traffic from a set of Pods inside the
cluster. This enables a few trusted applications to reach out from the application on all ports and is especially useful
when workloads in a cluster communicate with each other over many random ports. The opening of traffic from
certain Pods is achieved by using labels as described in the policy below.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: web-allow-internal-port80
spec:
podSelector:
matchLabels:
app: “myapp”
role: “web”
ingress:
- ports:
- port: 8080
from:
- podSelector:
matchLabels:
app: “mytestapp”
role: “web-test-client”
Even if a Service listens on a different port than where the Pod’s containers listen, use the container ports in
the network policy. Ingress rules affect inter-Pod communication, and the policy does not know about the
abstraction of the service.
The specification requires that providers implement their plugin as a binary executable that the container engine
invokes. Kubernetes does this via the Kubelet process running on each node of the cluster.
The CNI specification expects the container runtime to create a new network namespace before invoking the CNI
plugin. The plugin is then responsible for connecting the container’s network with that of the host. It does this by
creating the virtual Ethernet devices that we discussed earlier.
To use the CNI plugin, pass --network-plugin=cni to the Kubelet when launching it. If your environment is not using
the default configuration directory (/etc/cni/net.d), pass the correct configuration directory as a value to --cni-
conf-dir. The Kubelet looks for the CNI plugin binary at /opt/cni/bin, but you can specify an alternative location
with --cni-bin-dir.
The CNI plugin provides IP address management for the Pods and builds routes for the virtual interfaces. To do
this, the plugin interfaces with an IPAM plugin that is also part of the CNI specification. The IPAM plugin must also
be a single executable that the CNI plugin consumes. The role of the IPAM plugin is to provide to the CNI plugin the
gateway, IP subnet, and routes for the Pod.
Once Flannel is running, it is not possible to change the network address space or the backend communication format
without cluster downtime.
— Good performance
Non Overlay Host-gw
— Cloud agnostic
— Good performance
Non Overlay AWS VPC
— Limited to Amazon’s cloud
The VxLAN backend creates a Flannel interface on every host. When a container on one node wishes to send traffic to
a different node, the packet goes from the container to the bridge interface in the host’s network namespace. From
there the bridge forwards it to the Flannel interface because the kernel route table designates that this interface
is the target for the non-local portion of the overlay network. The Flannel network driver wraps the packet in a UDP
packet and sends it to the target host.
Once it arrives at its destination, the process flows in reverse, with the Flannel driver on the destination host
unwrapping the packet, sending it to the bridge interface, and from there the packet finds its way into the overlay
network and to the destination Pod.
Unlike VxLAN, no Flannel interface is created when using this backend. Instead, each node sends traffic directly to the
destination node where the remote network is located.
This backend may require additional network configuration if used in a cloud provider where inter-host communication
uses virtual switches.
UDP
The UDP backend is insecure and should only be used for debugging or if the kernel does not support VxLAN.
Calico supports network policies for protecting workloads and nodes from malicious activity or
aberrant applications.
The Calico networking Pod contains a CNI container, a container that runs an agent that tracks Pod deployments
and registers addresses and routes, and a daemon that announces the IP and route information to the network
via the Border Gateway Protocol (BGP). The BGP daemons build a map of the network that enables cross-host
communication.
Calico requires a distributed and fault-tolerant key/value datastore, and deployments often choose etcd to deliver
this component. Calico uses it to store metadata about routes, virtual interfaces, and network policy objects. The
Felix agent in the calico-node Pod communicates with etcd to publish this information. Calico can use a dedicated
HA deployment of etcd, or it can use the Kubernetes etcd datastore via the Kubernetes API. Please see the Calico
deployment documentation to understand the functional restrictions that are present when using the Kubernetes
API for storing Calico data.
The final piece of a Calico deployment is the controller. Although presented as a single object, it is a set of controllers
that run as a control loop within Kubernetes to manage policy, workload endpoints, and node changes.
— The Policy Controller watches for changes in the defined network policies and translates them into Calico
network policies.
— The Node Controller loop watches for the addition or removal of Kubernetes nodes and updates the kvdb with
the corresponding data.
Users can manage Calico objects within the Kubernetes cluster via the command-line tool calicoctl. The tool’s
only requirement is that it can reach the Calico datastore.
In the output below, note that the routing table indicates that a local interface (cali106d129118f) handles traffic for
the IP address of the Pod. The calico-node Pod creates this interface and propagates the routes to other nodes in
the cluster.
Kubernetes scheduled our Pod to run on k8s-n-1. If we look at the route table on the other two nodes, we see that
each directs 192.168.2.0/24 to 70.0.80.117, which is the address of k8s-n-1.
Two configurations of route reflectors: a single route reflector (top) and multiple route reflectors configured within a
Kubernetes cluster (bottom).
Before we can use a route reflector, we first have to disable the default node-to-node BGP peering in the Calico
configuration. We do this by setting nodeToNodeMeshEnabled to false in the BGPConfiguration resource, as
demonstrated below:
apiVersion: projectcalico.org/v3
kind: BGPConfiguration
metadata:
name: default
spec:
logSeverityScreen: Info
nodeToNodeMeshEnabled: false
asNumber: 63400
The calico-node Pods use one of two methods to build the peering relationship with external peers: global peering
or per-node peering.
Use the ASN retrieved above and the IP of the external peer.
You can view the current list of BGP Peers with the following:
As before, use the ASN for the Calico network and the IP of the BGP peer. Specify the node to which this configuration
applies.
Using IP-in-IP
If we’re unable to use BGP, perhaps because we’re using a cloud provider or another environment where we have
limited control over the network or no permission to peer with other routers, Calico’s IP-in-IP mode encapsulates
packets before sending them to other nodes.
To enable this mode, define the ipipMode field on the IPPool resource:
apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
name: project1IPPool
spec:
cidr: 10.11.12.0/16
ipipMode: CrossSubnet
natOutgoing: true
After activating IP-in-IP, Calico wraps inter-Pod packets in a new packet with headers that indicate the source of the
packet is the host with the originating Pod, and the target of the packet is the host with the destination Pod. The Linux
kernel performs this encapsulation and then forwards the packet to the destination host where it is unwrapped and
delivered to the destination Pod.
1.
Always: This is the default mode if an IPPool resource is defined.
2.
CrossSubnet: This only performs IP encapsulation for traffic which crosses subnet boundaries. Doing this
provides a performance benefit on networks where cluster members within separate Layer 2 boundaries have
routers between them because it performs encapsulation intelligently, only using it for the cross-subnet traffic.
For the CrossSubnet mode to work, each Calico node must use the IP address and subnet mask for the host. For
more information on this, see the Calico documentation for IP-in-IP.
Multus supports the multi-networking feature in Kubernetes using Custom Resources Definition (CRD)-based
network objects to extend the Kubernetes application programming interface (API). This function is important
because multiple interfaces are employed by network functions to separate control, management and data/user
network planes. Interfaces are also used to support different protocols, software stacks, tuning, and configuration
requirements. Multus enables pods not only have multiple network interface connections, but also use advanced
networking functions—including port mirroring and bandwidth capping—attached to those interfaces.
The illustration below shows network interfaces attached to a pod with three interfaces, as provisioned by Multus
CNI: eth0, net0 and net1. eth0 connects Kubernetes cluster network to connect with Kubernetes server/services (e.g.
Kubernetes api-server, kubelet and so on). net0 and net1 are additional network attachments and connect to other
networks by using other CNI plugins (e.g. vlan/vxlan/ptp).
Kubernetes servers
(api-server, kubelet son on)
other networks
Network Attachments
Pod
net0
NW2
net1 eth0
For a quickstart with Multus, you need to have configured a default network—that is, a CNI plugin that’s used for your
pod-to-pod connectivity—and a Kubernetes CNI plugin to serve as your pod-to-pod network. The recommended
method is to deploy Multus using a Daemonset that spins up pods which install a Multus binary and configure Multus
for usage.
— Starts a Multus daemonset that places a Multus binary on each node in /opt/cni/bin
— Reads the first alphabetical configuration file in /etc/cni/net.d, and auto-generates a new configuration file
for Multus as /etc/cni/net.d/00-multus.conf
— Creates a /etc/cni/net.d/multus.d directory on each node with authentication information for Multus to
access the Kubernetes API.
It’s possible to further validate by looking at the /etc/cni/net.d/ directory and ensuring that the auto-generated /
etc/cni/net.d/00-multus.conf corresponds to the first configuration file.
CNI Configurations
CNI configurations are JSON, with a structure that has several key features:
1.
cniVersion: Defines the version used for each CNI plugin.
2.
type: Commands CNI which binary to call on disk. Typically, these binaries are stored in /opt/cni/bin on each
node, and CNI executes this binary. This example specifies the loopback binary (which create a loopback-type
network interface). If this is your first time installing Multus, verify that the plugins that are in the “type” field are
actually on disk in the
/opt/cni/bin directory.
3.
additional: This field is an example. Each CNI plugin can specify a JSON configuration parameter, specific to the
binary being called in the type field.
{
“cniVersion”: “0.3.0”,
“type”: “loopback”,
“additional”: “information”
}
It is not necessary to reload or refresh the Kubelets when CNI configurations change because they are read on each
creation / deletion of pods. When a configuration changes, it will apply the next time a pod is created. It may be
necessary to restart existing pods that need the new configuration.
Give the configuration a name using the name field under metadata —this is also how to tell pods to use this
configuration. The name in this example is macvlan-conf—because the demonstration creates a configuration for
macvlan.
This example uses eth0 as the master parameter. The master parameter should match the interface name on the
host’s cluster. Use kubectl to see the new configurations via:
The following command reveals the interfaces are attached to the pod:
— lo a loopback interface
— eth0 our default network
— net1 the new interface we created with the macvlan configuration.
[{
“name”: “cbr0”,
“ips”: [
“10.244.1.73”
],
“default”: true,
“dns”: {}
},{
“name”: “macvlan-conf”,
“interface”: “net1”,
“ips”: [
“192.168.1.205”
],
“mac”: “86:1d:96:ff:55:0d”,
“dns”: {}
}]
It is possible to add more interfaces to a pod by creating more custom resources, then referring to them in pod’s
annotation. It is also feasible to reuse configurations. To attach two macvlan interfaces to a pod, create a pod like so:
eBPF can run sandboxed programs in an operating system kernel, enabling users to safely and efficiently extend
the capabilities of the kernel without changing kernel source code, loading kernel modules, or changing container
configuration. This enables dynamic insertion of powerful security visibility and control logic within Linux.
By leveraging Linux eBPF, Cilium can insert security visibility and enforcement based on service / pod / container
identity, in contrast to IP address identification in traditional systems. It can also filter on application-layer (e.g.
HTTP). As a result, Cilium decouples security from addressing, and provides stronger security isolation by operating
at the HTTP-layer in addition to providing traditional Layer 3 and Layer 4 segmentation.
— Allow all HTTP requests with method GET and path /public/.*. Deny all other requests.
— Allow service1 to produce on Kafka topic topic1 and service2 to consume on topic1. Reject all other Kafka
messages.
— Require the HTTP header X-Token: [0-9]+ to be present in all REST calls.
4. Simple Networking
Cilium offers a simple, flat Layer 3 network with the ability to span multiple clusters connecting all application
containers. IP allocation uses host scope allocators, so that each host can allocate IPs without any coordination
between hosts. Cilium supports the following multi node networking models:
— Overlay: Cilium offers encapsulation-based virtual network spanning all hosts. VXLAN and Geneve are baked
in but users can enable all encapsulation formats supported by Linux. This mode has minimal infrastructure
— Native Routing: Cilium enables use of the regular routing table of the Linux host. The network must be capable to
route the IP addresses of the application containers. This mode is for advanced users and requires awareness of
the underlying networking infrastructure. It works especially well with:
For north-south type load balancing, Cilium’s eBPF implementation is optimized for maximum performance. It can
be attached to XDP (eXpress Data Path) and it supports direct server return (DSR), as well as Maglev consistent
hashing. For east-west type load balancing, Cilium performs efficient service-to-backend translation in the Linux
kernel’s socket layer (e.g. at TCP connect time) to avoid per-packet NAT operations overhead in lower layers.
6. Bandwidth Management
Cilium implements bandwidth management through efficient EDT-based (Earliest Departure Time) rate-limiting
with eBPF for container traffic as it leaves a node. Compared to traditional approaches such as HTB (Hierarchy
Token Bucket) or TBF (Token Bucket Filter) as used in the bandwidth CNI plugin, Cilium can reduce transmission tail
latencies for applications and helps avoid locking under multi-queue NICs.
— Event monitoring with metadata: When a packet is dropped, the tool reports the source and destination IP of the
packet, as well as the full label information of both the sender and receiver.
— Policy decision tracing, to help understand why a packet is being dropped or a request rejected.
— Metrics export via Prometheus for integration with dashboards.
— Hubble, an observability platform written for Cilium, offers service dependency maps, operational monitoring
and alerting, and flow log-based application and security visibility.
Requirements
Most modern Linux distributions meet the minimum requirements for Cilium:
1. Running Cilium using the container image cilium/cilium requires the host system to meet these requirements:
2. Running Cilium as a native process on your host (i.e. not running the cilium/cilium container image) entails
these additional requirements:
As a first step, install a cluster based on the RKE Installation Guide. When creating the cluster, make sure to change
the default network plugin in the config.yaml file by changing this:
Network:
options:
flannel_backend_type:“vxlan”
plugin: “canal”
To this:
network:
plugin: none
Then, install Cilium via the provided quick-install.yaml. (Note that quick-install.yaml is a pre-rendered Cilium
chart template. The template is generated using helm template command with default configuration parameters
without any customization.)
kubectl apply -f
https://raw.githubusercontent.com/cilium/cilium/v1.9/install/kubernetes/quick-install.yaml
This test implements a series of deployments using various connectivity paths to connect. Connectivity paths include
with / without service load-balancing, as well as and various network policy combinations. The pod name indicates the
connectivity variant and the readiness; the liveness gate indicates success or failure of the test:
kubectl apply -f
https://raw.githubusercontent.com/cilium/cilium/v1.9/install/kubernetes/quick-hubble-
install.yaml
Once the Hubble UI pod is started, use port forwarding for the hubble-ui service. This allows opening the UI locally on a
browser:
Hubble UI is not the only way to get access to Hubble data. A command line tool, the Hubble CLI, is also available
for installation for Linux, MacOS, and Windows users. Additional methods to implement Hubble are available in the
installation documentation for RKE.
Kube-Vip offers two main technologies to provide high-availability and networking functions as part of a VIP/Load-
balancing solution.
1. Cluster
The kube-vip service builds a multi-node or multi-pod cluster to provide HA. In ARP mode, a leader is elected, which
inherits the Virtual IP and becomes the leader of the load-balancing within the cluster. With BGP, all nodes will advertise
the VIP address. When using ARP or layer2, Kube-Vip uses leader election.
2. Virtual IP
The leader in the cluster assumes the vip
and has it bound to the selected interface
declared in the configuration. The vip is kube-system
Users can expect easy manifest deployment, support for management via BGP or ARP (Address resolution protocol)
functionality, with support from core Equinix Metal integration (such as CCM, Packet API).
While Kube-Vip was originally created to provide a HA solution for the Kubernetes control plane, it has evolved to
incorporate that same functionality into Kubernetes service type load-balancers. VIP addresses can be both IPv4 or
IPv6. The Control Plane features ARP (Layer 2) or BGP (Layer 3), using either leader election or raft, with HA facilitated
by kubeadm (static Pods) or K3s/and others (daemonsets).
The Service LoadBalancer uses leader election for ARP (Layer 2), and multiple nodes with BGP. Users can address
pools per namespace or global, address via an existing network DHCP, or exposure to gateway via UPNP.
Note that the “hybrid” mode is now the default mode in kube-vip from 0.2.3 onwards. It allows both modes to be
enabled at the same time.
Generate a Manifest
Next, generate a simple BGP configuration by setting the configuration details as follows:
export VIP=192.168.0.40
export INTERFACE=<interface>
containerd
alias kube-vip=”ctr run --rm --net-host ghcr.io/kube-vip/kube-vip:0.3.7 vip”
Docker
alias kube-vip=”docker run --network host --rm ghcr.io/kube-vip/kube-vip:0.3.7”
export INTERFACE=lo
Generated Manifest
apiVersion: apps/v1
kind: DaemonSet
metadata:
creationTimestamp: null
name: kube-vip-ds
namespace: kube-system
spec:
selector:
matchLabels:
name: kube-vip-ds
template:
metadata:
creationTimestamp: null
labels:
name: kube-vip-ds
spec:
containers:
- args:
- manager
env:
- name: vip_arp
value: “false”
- name: vip_interface
value: lo
- name: port
value: “6443”
Manifest Overview
— nodeSelector – This feature ensures that the particular daemonset runs only on control plane nodes
— serviceAccountName: kube-vip – This feature specifies the user in the rbac to provide permissions to receive/
update services
— hostNetwork: true – This feature entails a pod that modifies interfaces (for VIPs)
— env {...} – This configuration is passed into the kube-vip pod through environment variables
If kube-vip has been waiting for a long time, confirm that the annotations have been applied correctly by
running the describe on the node as follows:
If you find errors regarding 169.254.255.1 or 169.254.255.2 in the kube-vip logs, it is possible that the
nodes are missing the routes to the ToR switches providing BGP peering. Nodes can be replaced with the
below command:
GATEWAY_IP=$(curl https://metadata.platformequinix.com/metadata | jq -r
“.network.addresses[] | select(.public == false) | .gateway”)
ip route add 169.254.255.1 via $GATEWAY_IP
ip route add 169.254.255.2 via $GATEWAY_IP
You can also examine the logs of the Packet CCM to reveal why the node is not yet ready.
Step 1: Tidy Up
Run the following:
export EIP=x.x.x.x
export INTERFACE=lo
Step 4: Up Cluster
Run:
k apply -f https://gist.githubusercontent.com/
thebsdbox/c86dd970549638105af8d96439175a59/
raw/4abf90fb7929ded3f7a201818efbb6164b7081f0/ccm.yaml
— A Kubernetes cluster running Kubernetes 1.13.0 or later, without existing network load-balancing functionality.
— A cluster network configuration that compatible with MetalLB. These include Calico, Canal, Cilium, Flannel, Kube-
ovn, Kube-router, and Weave Net.
Note that MetalLB is designed for bare-metal clusters. Generally, even cloud providers that offer “dedicated servers”
will not support the network protocols that MetalLB requires.
and set:
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
mode: “ipvs”
ipvs:
strictARP: true
You may also add this configuration snippet to kubeadm-config, if it is appended with --- after the main
configuration.
Installation by Manifest
To install MetalLB using manifest, apply:
This deploys MetalLB to the cluster under the metallb-system namespace. Manifest components include:
— Service accounts for the controller and speaker, plus RBAC permissions required by the components to function.
The installation manifest does not include a configuration file. MetalLB’s components will still start, but will remain
idle until you define and deploy a configmap.
# kustomization.yml
namespace: metallb-system
resources:
- github.com/metallb/metallb//manifests?ref=v0.11.0
- configmap.yml
# kustomization.yml
namespace: metallb-system
resources:
- github.com/metallb/metallb//manifests?ref=v0.11.0
configMapGenerator:
- name: config
files:
- configs/config
generatorOptions:
disableNameSuffixHash: true
You may specify a values file on installation. This is recommended practice to provide configs in Helm values:
configInline:
address-pools:
- name: default
protocol: layer2
addresses:
- 198.51.100.0/24
Load Distribution
When client requests arrive, the load balancer directs them across a pool of worker nodes commonly referred to
as backends. Because the load balancer presents itself as the endpoint for the site, the clients don’t know anything
about these backends. The load balancer tracks the health and number of connections to each backend, and it
works according to its configured policy to evenly distribute the traffic. If a backend fails or becomes overloaded, the
load balancer stops sending traffic to it until it returns to a healthy state. This scenario enables horizontal scaling,
where a site can scale
capacity by adding and
removing backends.
Host
Request A
Load Balancer
Host
Request B
Host
Request C
www-backend
www-1
Neutral Component
CLI www-2
User haproxy-www
Load Balancer
1 Container
Active
web.example.com
Letchat 1 Letchat 2
2 containers 2 containers
Active Active
Ngmix 1 Ngmix 2
2 containers 2 containers
Active Active
Mongo
1 container
web.example.com/support web.example.com/career
Active
Load Balancer
V1 V1 V1
V2
Load Balancer
V2 V1 V1
Load balancers also provide a way to roll out upgrades safely. Site administrators first deploy the new version of
the website or application to a new set of backends and test it outside of the standard rotation. When ready, they
incrementally add the new backends to the pool and rotate the old backends out. The load balancers keep existing
traffic on the old backends and direct new traffic to the new backends. Over time the sessions connected to the old
backends close, and only new sessions remain. The old backends are then terminated.
In the event of an unforeseen issue, the admins can quickly rotate the old backends into the pool and remove the
new ones, returning the site to its previous, working state.
Load Balancer
1
Neutral Neutral Neutral Neutral
Servers >> Component Component Component Component
Load Balancer
2
Neutral Neutral Neutral Neutral
Component Component Component Component
Load Balancer
3
Neutral Neutral Neutral Neutral
Component Component Component Component
Load Balancer
4
Neutral Neutral Neutral Neutral
Component Component Component Component
After
They only abandoned the name and status; the result remains the same. Flannel provides an overlay network using
one of its backends, and Calico provides granular access control to the running workloads with its network policy
implementation.
Canal
Orchestrator
Calico CNI Plugin flannel CNI plugin
Plugins
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 9376
When traffic arrives at the Service, kube-proxy forwards it to the appropriate backend.
Host
Client apiserver
A Kubernetes Service of the type LoadBalancer creates a Layer 4 load balancer outside of the cluster, but it only
does this if the cluster knows how. External load balancers require that the cluster use a supported cloud provider
in its configuration and that the configuration for the cloud provider includes the relevant access credentials when
required.
Once created, the Status field of the service shows the address of the external load balancer.
Invoked on Kubernetes LB
create/update
Workload
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 9376
clusterIP: 10.0.171.239
loadBalancerIP: 78.11.24.19
type: LoadBalancer
status:
loadBalancer:
ingress:
- ip: 146.148.47.155
Furthermore, because the LoadBalancer Service type requires a supported external cloud provider, and because
Kubernetes only supports a small number of providers, many sites instead choose to run a Layer 7 load balancer inside
of the cluster.
Layer 7
The Kubernetes resource that handles load balancing at Layer 7 is called an Ingress, and the component that creates
Ingresses is known as an Ingress Controller.
The following manifest defines an Ingress for the site foo.bar.com, sending /foo to the s1 Service and /bar
to the s2 Service:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: test
annotations:
nginx.ingress.Kubernetes.io/rewrite-target: /
spec:
rules:
- host: foo.bar.com
http:
paths:
- path: /foo
backend:
serviceName: s1
servicePort: 80
- path: /bar
backend:
serviceName: s2
servicePort: 80
When working with an external load balancer the Ingress Controller is a lightweight component that translates the
Ingress resource definitions from the cluster into API calls that configure the external piece.
Runs as a Kubernetes
application
Cloud Load Balancer
Listens to ingress
create/update events
Website Nodeport Service Chat Nodeport Service Website Nodeport Service Chat Nodeport Service
The following diagram shows a Nginx Ingress Controller working within a cluster.
Runs as a Kubernetes
Native App
Nginx Daemonset
Node Node
Kubernetes uses annotations to control the behavior of the Ingress Controller. Although each controller has a list
of accepted annotations, their use activates advanced features such as canary deployments, default backends,
timeouts, redirects, CORS configuration, and more.
First, load balancers can only handle one IP address per service, which means if you run multiple services in your
cluster, you must have a load balancer for each service. Running multiples load balancers can be expensive.
Second, if you want to use a load balancer with a Hosted Kubernetes cluster (i.e., clusters hosted in GKE, EKS,
or AKS), the load balancer must be running within that cloud provider’s infrastructure. In other words, cluster
deployments on Amazon EKS, Google GKE, Azure AKS, and RKE on EC2 are supported by layer-4 load balancers
from their respective cloud provider. Amazon EKS and Google GKE provide layer-7 load balancer support; layer 7
load balancer support on RKE on EC2 is provided by Nginx Ingress Controller, and is not supported on Azure AKS.
On cloud providers which support external load balancers, setting the type field to LoadBalancer provisions
a load balancer for your Service. The actual creation of the load balancer happens asynchronously, and
information about the provisioned balancer is published in the Service’s .status.loadBalancer field
For example:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 9376
clusterIP: 10.0.171.239
type: LoadBalancer
status:
loadBalancer:
ingress:
- ip: 192.0.2.127
Traffic from the external load balancer is directed at the backend Pods. The cloud provider decides how it is
load balanced.
Some cloud providers allow you to specify the loadBalancerIP, in which case the load-balancer is created with
the user-specified loadBalancerIP. If the loadBalancerIP field is not specified, the loadBalancer is set up with
an ephemeral IP address. If you specify a loadBalancerIP but your cloud provider does not support the feature,
the loadbalancerIP field that you set is ignored.
Additional documentation from Kubernetes can help you properly configure your load balancer for a given
cloud provider.
Thank You
© 2022 SUSE LLC. All Rights Reserved. SUSE and the SUSE
logo are registered trademarks of SUSE LLC in the United
States and other countries. All third-party trademarks are
the property of their respective owners.