Basics of Kubernetes Networking

Kubernetes provides an abstraction over a network of nodes, making it easier to deploy and manage distributed systems. Here are the key aspects:

  1. Pod IP Addresses: Each Pod gets its own IP address, making it directly accessible to other Pods in the cluster.
  2. DNS Service: Kubernetes provides built-in DNS for service discovery.
  3. Isolation: Network Policies can be used to control the communication between Pods.

Pod-to-Pod Communication

In Kubernetes, Pods can communicate with each other directly using their IP addresses.

Example: Ping between Pods

First, create two Pods:

``` kubectl run pod2 --image=busybox --command -- sleep 3600

Get the IP address of `pod2`:

``` kubectl get pod pod2 -o=jsonpath='{.status.podIP}'

Ping `pod2` from `pod1`:

``` kubectl exec -it pod1 -- ping <pod2-ip>

### Service Networking

Services are abstractions that provide network endpoints to access Pods. They provide stable IPs and DNS names.

**Example: Creating a Service**

Deploy a simple HTTP server:

``` kubectl run http-server --image=httpd --port=80

Create a service for the HTTP server:

``` kubectl expose pod http-server --port=80 --name=http-service

Access the service within the cluster:

``` kubectl run curlpod --image=busybox -it --rm -- /bin/sh -c 'wget -O- http-service'

### Ingress and Egress

**Ingress**: Allows external access to services within the cluster.
**Egress**: Controls the outbound traffic from Pods.

**Example: Simple Ingress**

Create an ingress.yaml file:

``` echo '
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: simple-ingress
spec:
  rules:
  - http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: http-service
            port:
              number: 80
' > ingress.yaml

Apply the ingress resource:

``` kubectl apply -f ingress.yaml

### Network Plugins and CNI (Container Network Interface)

Kubernetes uses CNI plugins to manage Pod networking.

**Example: Using Calico**

Install Calico:

``` kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml

### Complete Exercise

**Setup**

1. Install Minikube
2. Start a Minikube cluster: `minikube start`

**Steps**

1. Deploy two Pods and make them communicate.
2. Expose one Pod via a service.
3. Create an Ingress to expose the service externally.
4. Install a CNI plugin.

**Troubleshooting**

1. Check pod status: `kubectl get pods`
2. Check logs: `kubectl logs <pod-name>`
3. Describe resource: `kubectl describe <resource> <name>`

**Solution**

1. Pods should be able to ping each other.
2. Service should distribute traffic to its Pod.
3. Ingress should expose the service to external traffic.
4. Network policies should work as expected if CNI is installed correctly.