CodeBlanks Logo Icon CodeBlanks

Multi-container Pod

Learn to run multiple containers in a Pod.

Multi-container pods

Several containers are put in one pod only if they are tightly coupled. The most common pattern is the sidecar: a container helping the main application (log collector, proxy, syncer). They share files through a common emptyDir volume:

spec:
  volumes:
    - name: loglar
      emptyDir: {}
  containers:
    - name: uygulama
      image: api:1.0
      volumeMounts:
        - name: loglar
          mountPath: /var/log/app
    - name: log-gonderici
      image: busybox:1.36
      command: ["sh", "-c", "tail -F /loglar/app.log"]
      volumeMounts:
        - name: loglar
          mountPath: /loglar

Init containers

initContainers are containers that run in order and finish before the main containers. They are used to wait for a dependency to be ready or to prepare configuration files; the main containers don't start until all of them finish successfully:

spec:
  initContainers:
    - name: db-bekle
      image: busybox:1.36
      command: ["sh", "-c", "until nc -z db 5432; do sleep 2; done"]
  containers:
    - name: api
      image: api:1.0

For a specific container's log, kubectl logs api -c db-bekle is used.

Practice A pod with a sidecar

Write a pod YAML: name api; a loglar volume with emptyDir: {} under volumes; two containers: uygulama (api:1.0, mounts loglar at /var/log/app) and log-gonderici (busybox:1.36, mounts loglar at /loglar).

Starter code

terminal
# buraya yaz

Sample solution

terminal
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  volumes:
    - name: loglar
      emptyDir: {}
  containers:
    - name: uygulama
      image: api:1.0
      volumeMounts:
        - name: loglar
          mountPath: /var/log/app
    - name: log-gonderici
      image: busybox:1.36
      volumeMounts:
        - name: loglar
          mountPath: /loglar

Expected output

pod/api created
NAME   READY   STATUS    RESTARTS   AGE
api    2/2     Running   0          9s

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Should a web application and a database be put in the same pod?

  • Only in production
  • Only in Minikube
  • No; they scale separately and have separate life cycles Correct answer
  • Yes, always

Explanation: When a pod scales, all containers in it are copied together.

2 Show the log of a specific container in the pod.

Question
kubectl logs api ____ db-bekle
Answer
kubectl logs api -c db-bekle

Explanation: -c (container) selects the container name.

3 Match.

Term Meaning
sidecar Helper container
emptyDir Pod-lifetime shared directory
initContainers Runs first and finishes
-c Container selection

All lessons in Intermediate