Friday, 10 October 2025

Kubernetes Sidecar Pattern: Ship Nginx Logs with Ubuntu in a Shared Volume

Our course you can check :-   Udemy course 

Ques:-    


We have a web server container running the nginx image. The access and error logs generated by the web server are not critical enough to be placed on a persistent volume. However, Nautilus developers need access to the last 24 hours of logs so that they can trace issues and bugs. Therefore, we need to ship the access and error logs for the web server to a log-aggregation service. Following the separation of concerns principle, we implement the Sidecar pattern by deploying a second container that ships the error and access logs from nginx. Nginx does one thing, and it does it well—serving web pages. The second container also specializes in its task—shipping logs. Since containers are running on the same Pod, we can use a shared emptyDir volume to read and write logs.

Create a pod named webserver.

Create an emptyDir volume shared-logs.

Create two containers from nginx and ubuntu images with latest tag only and remember to mention tag i.e nginx:latest, nginx container name should be nginx-container and ubuntu container name should be sidecar-container on webserver pod.

Add command on sidecar-container "sh","-c","while true; do cat /var/log/nginx/access.log /var/log/nginx/error.log; sleep 30; done"

Mount the volume shared-logs on both containers at location /var/log/nginx, all containers should be up and running.


Ans:-

Here’s the full YAML manifest to create the webserver Pod with the Sidecar pattern using a shared emptyDir volume for logs:

raj@jumphost ~$ cat pod.yaml 

apiVersion: v1

kind: Pod

metadata:

  name: webserver

spec:

  volumes:

    - name: shared-logs

      emptyDir: {}

  containers:

    - name: nginx-container

      image: nginx:latest

      volumeMounts:

        - name: shared-logs

          mountPath: /var/log/nginx

    - name: sidecar-container

      image: ubuntu:latest

      command: ["sh", "-c", "while true; do cat /var/log/nginx/access.log /var/log/nginx/error.log; sleep 30; done"]

      volumeMounts:

        - name: shared-logs

          mountPath: /var/log/nginx


raj@jumphost ~$ kubectl apply -f pod.yaml


raj@jumphost ~$ kubectl get pod

NAME        READY   STATUS    RESTARTS   AGE

webserver   2/2     Running   0          77s


raj@jumphost ~$ kubectl logs webserver -c sidecar-container


2025/10/10 11:24:23 [notice] 1#1: using the "epoll" event method

2025/10/10 11:24:23 [notice] 1#1: nginx/1.29.2


Explanation:

  • Pod name: webserver
  • Volume: shared-logs of type emptyDir (non-persistent, shared between containers)
  • Containers:
    • nginx-container: runs nginx:latest, mounts /var/log/nginx
    • sidecar-container: runs ubuntu:latest, reads logs every 30 seconds using a shell loop

No comments:

Post a Comment