Advanced Usage: The Sidecar Pattern

In Kubernetes, the sidecar pattern involves co-locating a helper container with the main application container within the same Pod. Because containers in a Pod share the same network namespace, a netshoot sidecar can be a powerful tool for continuous monitoring or on-demand troubleshooting.

By deploying netshoot alongside your application, you gain immediate shell access to the Pod's network environment without needing to use ephemeral containers. This can be useful in environments where ephemeral containers are disabled or for setting up long-running diagnostic processes.

Example: Nginx with a Netshoot Sidecar

Below is a Kubernetes Deployment manifest that deploys a Pod containing two containers: nginx (the main application) and netshoot (the sidecar).

apiVersion: apps/v1
kind: Deployment
metadata:
    name: nginx-netshoot
    labels:
        app: nginx-netshoot
spec:
 replicas: 1
 selector:
    matchLabels:
        app: nginx-netshoot
 template:
    metadata:
     labels:
        app: nginx-netshoot
    spec:
        containers:
        - name: nginx
          image: nginx:1.14.2
          ports:
            - containerPort: 80
        - name: netshoot
          image: nicolaka/netshoot
          # This command keeps the container running indefinitely
          command: ["/bin/bash"]
          args: ["-c", "while true; do ping localhost; sleep 60;done"]

Breakdown of the Manifest

  • spec.containers: This array defines the two containers that will run in the Pod.
  • name: nginx: The primary application container.
  • name: netshoot: The sidecar container.
  • command and args: In the netshoot container, we specify a command that runs an infinite loop. This is crucial because a container will exit if its main process finishes. This simple loop ensures the netshoot container stays alive, ready for you to access.

How to Use the Sidecar

  1. Apply the manifest:

    kubectl apply -f netshoot-sidecar.yaml
  2. Verify the Pod is running:

    You should see 2/2 in the READY column, indicating both containers are running.

    kubectl get pod
    # NAME                              READY   STATUS    RESTARTS   AGE
    # nginx-netshoot-7f9c6957f8-kr8q6   2/2     Running   0          4m27s

  3. Execute a shell in the netshoot container:

    Use kubectl exec to get a shell inside the netshoot sidecar. The -c netshoot flag specifies which container in the Pod to connect to.

    kubectl exec -it <pod_name> -c netshoot -- /bin/zsh

Now you are inside the Pod's network namespace with all of netshoot's tools at your disposal.