How Services Work
About 1979 words
1. Kubernetes Service Overview
A Kubernetes Service is a core abstraction that provides a stable network endpoint for applications running in a cluster. It addresses connectivity problems caused by the dynamic nature of Pods:
Challenges of dynamic Pods:
- Pods are ephemeral and can be created or destroyed at any time.
- Pod IPs can change after restarts or migration.
- Deployment size can scale dynamically.
What Services provide:
- A stable virtual IP (VIP) and DNS name.
- Automatic load balancing across backend Pods.
- Service discovery.
- Multiple ways to expose services.
2. The Service VIP Mechanism
2.1 VIP Allocation and Management
A Service's ClusterIP is a virtual IP (VIP). Its lifecycle management includes:
IP allocation:
- kube-apiserver allocates it from the configured
service-cluster-ip-range. - The
--service-cluster-ip-rangeflag specifies the range, such as 10.96.0.0/12. - Addresses are allocated sequentially, with etcd ensuring atomicity.
- kube-apiserver allocates it from the configured
VIP characteristics:
- It is not bound to a physical or virtual network interface.
- It does not respond to ARP requests.
- It exists only in Kubernetes networking rules.
- It remains unchanged throughout its lifecycle, even if every backend Pod is replaced.
IP reclamation:
- Deleting a Service releases its ClusterIP.
- IP reuse can be configured.
2.2 How VIP Routing Works
Routing a VIP inside the cluster relies on the following mechanisms working together:
kube-proxy rule maintenance:
- Installs networking rules, using iptables or IPVS, on every node.
- Maps VIPs to actual Pod IPs.
CNI network plugins:
- Ensure all Pods share a flat network or are mutually routable.
- Maintain connectivity between nodes.
Kernel network stack:
- Implements address translation through netfilter.
- Uses the routing subsystem for final forwarding.
3. kube-proxy in Depth
3.1 Three kube-proxy Modes
3.1.1 userspace Mode (Deprecated)
How it works:
- kube-proxy watches Service and Endpoint changes from userspace.
- It opens a random port for each Service.
- iptables rules redirect traffic to that port.
- The kube-proxy process performs load balancing internally.
Drawbacks:
- High overhead from userspace/kernel-space context switching.
- Poor performance.
3.1.2 iptables Mode (Default)
Architecture:
+---------------------------------------------------+
| Pod A |
| Send request: curl 10.96.1.1:80 |
+---------------------------------------------------+
|
v
+---------------------------------------------------+
| Host network stack |
| PREROUTING -> KUBE-SERVICES -> KUBE-SVC-XXX |
| -> KUBE-SEP-XXX (DNAT) -> Routing decision |
+---------------------------------------------------+
|
v
+---------------------------------------------------+
| Pod B |
| Receive request: 10.244.1.2:80 |
+---------------------------------------------------+Example rules:
# Service entry rule
-A KUBE-SERVICES -d 10.96.1.1/32 -p tcp -m tcp --dport 80 -j KUBE-SVC-ABC123
# Load-balancing rule: choose the first backend with 50% probability
-A KUBE-SVC-ABC123 -m statistic --mode random --probability 0.5 -j KUBE-SEP-DEF456
-A KUBE-SVC-ABC123 -j KUBE-SEP-GHI789
# Endpoint DNAT rules
-A KUBE-SEP-DEF456 -p tcp -m tcp -j DNAT --to-destination 10.244.1.2:80
-A KUBE-SEP-GHI789 -p tcp -m tcp -j DNAT --to-destination 10.244.2.3:80Characteristics:
- Processing happens entirely in kernel space, providing good performance.
- Rule count grows linearly with Service and Pod counts.
- A simple load-balancing algorithm chooses randomly with equal probability.
3.1.3 IPVS Mode (Recommended for Production)
Architectural advantages:
+---------------------------------------------------+
| IPVS kernel module |
| +---------------------+ |
| | Virtual Service | 10.96.1.1:80 |
| +---------------------+ |
| | | |
| v v |
| +-----------+ +-----------+ |
| | Real Server | | Real Server | |
| | 10.244.1.2 | | 10.244.2.3 | |
| +-----------+ +-----------+ |
+---------------------------------------------------+Configuration example:
# Create a virtual service using round-robin scheduling
ipvsadm -A -t 10.96.1.1:80 -s rr
# Add real servers
ipvsadm -a -t 10.96.1.1:80 -r 10.244.1.2:80 -m # NAT mode
ipvsadm -a -t 10.96.1.1:80 -r 10.244.2.3:80 -mAdvantages:
- Multiple load-balancing algorithms: rr, wrr, lc, wlc, and others.
- O(1) time complexity, suitable for large clusters.
- Finer-grained traffic control.
3.2 Detailed kube-proxy Data Flow
3.2.1 Communication Between Pods on the Same Node
Packet path:
Pod egress:
- The application sends a request:
curl 10.96.1.1:80. - Packet: src=10.244.0.1, dst=10.96.1.1, dport=80.
- The application sends a request:
veth transmission:
- The packet leaves the Pod's network namespace through a veth pair.
- It reaches the host-side virtual interface, such as veth123.
Host network stack processing:
Routing decision:
- The kernel examines destination IP 10.244.1.2.
- The routing table identifies it as a local Pod.
- Example route:
10.244.1.0/24 dev cni0 scope link.
Bridge forwarding:
- The packet is forwarded through the cni0 bridge.
- It reaches the destination Pod's veth interface.
3.2.2 Communication Between Pods on Different Nodes
Key differences:
Routing stage:
- The kernel finds that the destination IP, such as 10.244.2.3, is not local.
- It looks up the node route:
10.244.2.0/24 via 192.168.1.2 dev eth0.
Cross-node transmission:
- Encapsulation depends on the CNI plugin: VXLAN, IPIP, or direct routing, for example.
- The destination node decapsulates the packet and forwards it to the destination Pod.
Return path:
- The destination Pod sends its response directly to the source Pod IP.
- Reverse translation through the Service VIP is not needed.
3.3 Key Network Stack Processing Order
Linux packet-processing flow:
+-----------------------+
| Outbound Pod packet |
+-----------------------+
|
v
+-----------------------+
| Host stack PREROUTING | <-- iptables rules run first
+-----------------------+
|
v
+-----------------------+
| Routing decision | <-- Based on the post-DNAT destination
+-----------------------+
|
v
+-----------------------+
| POSTROUTING | <-- Possible SNAT processing
+-----------------------+
|
v
+-----------------------+
| Egress interface |
+-----------------------+Key conclusions:
- DNAT precedes routing: iptables changes the destination address before the system makes its routing decision.
- The essence of Service access: The VIP is meaningful at the control-plane level; the data plane always uses real Pod IPs.
- Performance impact: In large clusters, the number of iptables rules affects networking performance.
4. Production Recommendations
4.1 Choosing a Mode
Small and medium clusters:
- The default iptables mode is sufficient.
- Performance is acceptable below 5,000 rules.
Large clusters:
- IPVS mode is recommended.
- Particularly suitable for many Services or frequent changes.
4.2 Performance Tuning
IPVS parameter tuning:
# Adjust the connection hash table size echo 2097152 > /sys/module/nf_conntrack/parameters/hashsize # Increase the IPVS connection table size ipvsadm --set 262144 262144iptables tuning:
- Periodically remove stale rules.
- Consider
--random-fullyto avoid port collisions.
4.3 Monitoring and Troubleshooting
Key metrics:
kube_proxy_sync_proxy_rules_duration_seconds: Rule synchronization duration.kube_proxy_network_programming_duration_seconds: Network programming latency.ipvs_connections: Current IPVS connections.
Common troubleshooting steps:
# Inspect iptables rules
iptables-save | grep KUBE-SVC
# Inspect IPVS configuration
ipvsadm -Ln
# Inspect routing tables
ip route show table all
# Inspect connection tracking
conntrack -L5. Summary
Kubernetes Services and kube-proxy together provide the foundation for service communication within a cluster:
Services provide a stable abstraction:
- VIPs hide changes to backend Pods.
- Multiple types meet different exposure requirements.
- Built-in load balancing.
kube-proxy implements the data plane:
- Multiple modes suit different cluster sizes.
- Kernel features enable efficient forwarding.
- Reacts to cluster state changes in real time.
How they cooperate:
Understanding these mechanisms helps with:
- Designing better microservice architectures.
- Troubleshooting networking efficiently.
- Optimizing performance for particular scenarios.
- Implementing security policies precisely.
Service implementations continue to evolve with the Kubernetes ecosystem, including Cilium's eBPF implementation. Their central idea remains the same: provide a stable, reliable network abstraction.
External Access in Kubernetes: externalIPs and NodePort Explained
1. Overview
A Kubernetes Service abstracts Pods and provides load balancing, with several mechanisms for exposing services to external networks. This article examines two important approaches, externalIPs and NodePort, including their operation, configuration, use cases, and best practices.
2. externalIPs in Depth
2.1 Basic Concepts
externalIPs is a Service field that allows administrators to specify one or more external IP addresses for exposing a service. Unlike automatically allocated LoadBalancer IPs, externalIPs require manual configuration and management.
2.2 How It Works
Traffic path:
- External client → designated externalIP → node network stack → kube-proxy → Service → Pod.
IP assignment requirements:
- The IP must be bound directly to a node network interface.
- Alternatively, it must be reachable through network routing, with routes configured correctly.
Multi-node handling:
- When an externalIP is configured on multiple nodes, kube-proxy ensures correct forwarding.
2.3 Configuration Guide
Basic YAML Example:
apiVersion: v1
kind: Service
metadata:
name: externalip-service
spec:
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 9376
externalIPs:
- 203.0.113.10
- 198.51.100.5Advanced Options:
- Multiple ports.
- Mixed protocols.
- Integration with sessionAffinity.
2.4 Network Infrastructure Requirements
IP allocation options:
- Static assignment to a node interface.
sudo ip addr add 203.0.113.10/24 dev eth0- DHCP reservation.
- Cloud platform floating IPs.
Routing configuration:
- Example static route on Cisco equipment:
ip route 203.0.113.10 255.255.255.255 <node-ip>Firewall rules:
- Open the required ports.
- Consider source IP restrictions.
2.5 Verification and Troubleshooting
- Verification steps:
# Inspect Service configuration
kubectl describe svc externalip-service
# Test connectivity
curl -v http://203.0.113.10:80
# Inspect node network configuration
kubectl get nodes -o wide
ssh node01 ip addr show | grep 203.0.113.10- Common problems:
- IP not correctly assigned to the node.
- Incorrect routes.
- Firewall blocks access.
- kube-proxy service issues.
3. NodePort in Depth
3.1 Basic Architecture
A NodePort Service exposes a static port on every node, in the default range 30000–32767, and forwards external traffic from that port to the Service.
Traffic Path:
External client → any node IP:NodePort → Service → Pod
3.2 Configuration
Basic YAML:
apiVersion: v1
kind: Service
metadata:
name: nodeport-demo
spec:
type: NodePort
selector:
app: MyApp
ports:
- name: http
port: 80
targetPort: 8080
nodePort: 31000Advanced Options:
- Custom port ranges.
- Multiple protocols.
- Selection of specific nodes.
3.3 Port Management
- Default range: 30000–32767.
- Changing the range requires modifying the API Server configuration:
# /etc/kubernetes/manifests/kube-apiserver.yaml
spec:
containers:
- command:
- kube-apiserver
- --service-node-port-range=30000-350003.4 Load-Balancing Strategies
Built-in load balancing:
- Uses kube-proxy's round-robin algorithm.
- Supports sessionAffinity.
External load balancer integration:
- Example cloud load balancer configuration, using AWS ALB:
resource "aws_lb_target_group" "example" { port = 31000 protocol = "HTTP" vpc_id = aws_vpc.main.id }
3.5 Security Best Practices
- NetworkPolicy:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: nodeport-allow
spec:
podSelector:
matchLabels:
app: MyApp
ingress:
- from:
- ipBlock:
cidr: 192.168.1.0/24
ports:
- protocol: TCP
port: 80- Additional security measures:
- Integrate TLS termination.
- Apply rate limiting.
- Enable access logging.
4. Comparing and Choosing the Approaches
4.1 Feature Comparison
| Feature | externalIPs | NodePort |
|---|---|---|
| IP management | Manual configuration | Automatic allocation |
| Port range | Any port | 30000–32767 |
| Load balancing | External implementation required | Additional LB needed across nodes |
| Cloud compatibility | Lower | High |
| Network requirements | Control of underlying network required | Standard networking is sufficient |
4.2 Performance Considerations
externalIPs:
- Direct routing offers lower latency.
- Suitable for high-throughput scenarios.
NodePort:
- Additional NAT introduces a small overhead.
- Clients must retry if a node fails.
4.3 Selection Recommendations
Choose externalIPs when:
- IP address requirements are strict.
- You control the underlying network infrastructure.
- Fixed, well-known ports are needed.
- Deploying on bare metal.
Choose NodePort when:
- Rapid prototyping is needed.
- Running in a cloud environment.
- Compatibility with other Service types is required.
- It serves as the underlying mechanism for Ingress or LoadBalancer.
5. Production Best Practices
5.1 Hybrid Architecture Example
A typical production architecture combining multiple Service types:
External users → Global LB → [ Regional LB → NodePort ] → Service → Pod
↑
externalIPs fallback path5.2 High Availability
externalIPs high availability:
- Use BGP for floating IPs.
- Combine with keepalived for failover.
NodePort high availability:
- Deploy multiple nodes.
- Use external health checks.
- Automatically remove unhealthy nodes.
5.3 Monitoring and Operations
Key metrics:
- Connection count.
- Latency.
- Error rate.
- Node resource utilization.
Example Prometheus configuration:
- job_name: 'nodeport_metrics'
metrics_path: /metrics
static_configs:
- targets: ['node1:31000', 'node2:31000']6. Summary
externalIPs and NodePort are both important Kubernetes service-exposure mechanisms, each with its own use cases. Understanding their operation, configuration details, and applicability is essential to designing reliable Kubernetes networking. In practice, select or combine approaches based on the infrastructure, security requirements, and performance needs.