- Multi-container pods are used in cases where it’s better to have separate code for some added functionality along with the application code. Example: log agent alongside the application to collect logs and send them to a centralized log server.
- Containers inside a pod share the same:
- Lifecycle - created and destroyed together
- Network - can refer each other as localhost
- Storage - can access the same storage volumes
- All the containers inside a pod must keep running for the pod to remain in running state. If any of them fails, the pod restarts.
Sharing volumes in multi-container pods
apiVersion: v1 kind: Pod metadata: name: web-pod spec: volumes: - name: shared-vol emptyDir: {} containers: - name: webapp image: webapp volumeMounts: - name: shared-vol mountPath: /files - name: log-agent image: log-agent volumeMounts: - name: shared-vol mountPath: /logs
Init Containers
Init containers run once during the pod initialization and they terminate after that. When a POD is first created, the init container is run, and the process in the init container must run to a completion before the real container hosting the application starts. We can have multiple init containers. In that case each init container is run one at a time in sequential order. If any of the init containers fail to complete, Kubernetes restarts the Pod repeatedly until all the init containers succeed.
For example: a process that pulls a code or binary from a repository that will be used by the main web application or a process that waits for an external service or database to be up before the actual application starts.
Init containers are defined just like other containers inside a pod definition file. However, they are defined under
initContainers
section.apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: myapp spec: containers: - name: myapp-container image: busybox:1.28 command: ['sh', '-c', 'echo The app is running! && sleep 3600'] initContainers: - name: init-myservice image: busybox:1.28 command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;'] - name: init-mydb image: busybox:1.28 command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']
Sidecar Containers
They are secondary containers that run along with the main container within the same Pod.
You have an application that is hard-coded to write log output to a file on disk.
You add a secondary container to the Pod that reads the log file from a shared volume and prints it to the console so the log output will appear in the container log.