Kubernetes Networking and Service Discovery
Kubernetes Networking Model
Kubernetes provides a unified networking model that allows Pods to communicate with each other and the outside world. The main components of the Kubernetes networking model are:
- Pod Network: Provides IP connectivity between Pods, allowing them to communicate with each other.
- Service Network: Provides a stable network endpoint for accessing applications running in Pods.
- Node Network: Provides network connectivity between Nodes, allowing Pods to communicate with the outside world.
graph TD
A[Kubernetes Cluster] --> B[Pod Network]
A --> C[Service Network]
A --> D[Node Network]
Kubernetes Services
Kubernetes Services provide a stable network endpoint for accessing applications running in Pods. There are several types of Services:
- ClusterIP: Exposes the Service on a cluster-internal IP address, allowing other Pods to access the Service.
- NodePort: Exposes the Service on each Node's IP address and a static port, allowing access from outside the cluster.
- LoadBalancer: Provisions a load balancer for the Service, providing a single, external IP address for accessing the application.
- ExternalName: Maps the Service to an external DNS name, allowing you to reference external services from within the cluster.
apiVersion: v1
kind: Service
metadata:
name: my-app
spec:
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
type: LoadBalancer
Service Discovery
Kubernetes provides several mechanisms for service discovery, allowing Pods to find and communicate with other services running in the cluster:
- Environment Variables: Kubernetes injects environment variables with information about other Services, such as their IP addresses and ports.
- DNS: Kubernetes provides a DNS server that resolves Service names to their corresponding IP addresses, allowing Pods to use Service names directly.
- Service Mesh: Tools like Istio and Linkerd provide advanced service discovery and communication features, including load balancing, traffic routing, and security.
graph TD
A[Pod] --> B[Environment Variables]
A --> C[DNS]
A --> D[Service Mesh]
Network Policies
Kubernetes Network Policies allow you to control the traffic flow between Pods, providing fine-grained network security. You can define rules to allow or deny traffic based on various criteria, such as source/destination IP addresses, ports, and labels.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-external-traffic
spec:
podSelector:
matchLabels:
app: my-app
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: my-app