In this lesson, we will explore the networking model of Kubernetes, focusing on Services and Ingress for traffic routing. Understanding how networking works in Kubernetes is crucial for deploying applications that can communicate effectively.
Kubernetes uses a flat networking model, which means that every pod can communicate with every other pod, regardless of the node they are running on. This is achieved through a virtual network that abstracts the underlying infrastructure.
A Service in Kubernetes can be of different types: - ClusterIP: Exposes the service on a cluster-internal IP. This is the default type. - NodePort: Exposes the service on each node’s IP at a static port. - LoadBalancer: Exposes the service externally using a cloud provider's load balancer.
Here’s how to create a simple ClusterIP service:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIP
To apply this configuration, save it to a file called my-service.yaml and run:
kubectl apply -f my-service.yaml
Once the service is created, you can access it using:
kubectl get services
This command will show you the ClusterIP assigned to your service. You can use this IP to access your application running in the Pods.
Ingress allows you to manage external access to your services. It can provide load balancing, SSL termination, and name-based virtual hosting.
Here’s an example of how to create an Ingress resource:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
Save this to a file called my-ingress.yaml and apply it with:
kubectl apply -f my-ingress.yaml
To access your application via Ingress, you will need to set up a DNS record pointing myapp.example.com to your Ingress controller's external IP.
Note: Always use the appropriate Service type based on your needs. For example, use
NodePortfor development but considerLoadBalancerfor production.Common Mistake: Forgetting to create the Ingress controller. Without it, your Ingress resources will not function.