Wednesday, September 10, 2025

How to setup a logger sidecar container in Kubernetes

 We’ll set up:

A main container (writes logs to a file).

A sidecar container (reads the log and prints it to stdout).

Deploy them together in a Pod.

Run it inside Minikube.


🔹 1. Kubernetes Pod YAML (main + sidecar)


Save as pod-sidecar.yaml:


apiVersion: v1

kind: Pod

metadata:

  name: main-sidecar-pod

spec:

  containers:

  - name: main-app

    image: busybox

    command: ["/bin/sh", "-c"]

    args:

      - |

        while true; do

          echo "$(date) : Hello from MAIN container" >> /var/log/app.log;

          sleep 5;

        done

    volumeMounts:

    - name: shared-logs

      mountPath: /var/log


  - name: sidecar-log-reader

    image: busybox

    command: ["/bin/sh", "-c"]

    args:

      - |

        tail -n+1 -f /var/log/app.log

    volumeMounts:

    - name: shared-logs

      mountPath: /var/log


  volumes:

  - name: shared-logs

    emptyDir: {}


What this does:

main-app writes a timestamped log to /var/log/app.log.

sidecar-log-reader tails the same log file (via emptyDir shared volume).

Both share the same directory /var/log.



🔹 2. Run on Minikube


Step 1: Start Minikube


minikube start


Step 2: Apply the Pod


kubectl apply -f pod-sidecar.yaml


Step 3: Verify the Pod


kubectl get pods


You should see:


main-sidecar-pod   Running   2/2   0   <time>


(2/2 containers means both main + sidecar are running.)



🔹 3. Check the logs


👉 Logs from sidecar (should continuously show main’s logs):


kubectl logs -f main-sidecar-pod -c sidecar-log-reader


👉 Logs from main (itself writes to file, not stdout):


kubectl exec -it main-sidecar-pod -c main-app -- tail -f /var/log/app.log




🔹 4. Clean up


kubectl delete pod main-sidecar-pod


No comments:

Post a Comment