Running a sidecar container to forward written logs

It can be difficult to modify our application to write logs to standard streams rather than log files, and we often want to avoid the troubles brought about by logging to hostPath volumes. In this situation, we could run a sidecar container to deal with logging for a pod. In other words, each application pod would have two containers sharing the same emptyDir volume, so that the sidecar container can follow logs from the application container and send them outside their pod, as shown in the following diagram:

Although we don't need to worry about managing log files anymore, chores such as configuring logging agents for each pod and attaching metadata from Kubernetes to log entries still takes extra effort. Another option would be to use the sidecar container to output logs to standard streams instead of running a dedicated logging agent, such as the following pod example. In this case, the application container unremittingly writes messages to /var/log/myapp.log and the sidecar tails myapp.log in the shared volume:

---7-2_logging-sidecar.yml---
apiVersion: v1
kind: Pod
metadata:
name: myapp
spec:
containers:
- image: busybox
name: application
args:
- /bin/sh
- -c
- >
while true; do
echo "$(date) INFO hello" >> /var/log/myapp.log ;
sleep 1;
done
volumeMounts:
- name: log
mountPath: /var/log
- name: sidecar
image: busybox
args:
- /bin/sh
- -c
- tail -fn+1 /var/log/myapp.log
volumeMounts:
- name: log
mountPath: /var/log
volumes:
- name: log
emptyDir: {}

We can see the written log with kubectl logs:

$ kubectl logs -f myapp -c sidecar
Sun Oct 14 21:26:47 UTC 2018 INFO hello
Sun Oct 14 21:26:48 UTC 2018 INFO hello ...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset