0
0
KubernetesHow-ToBeginner · 4 min read

How to Use Multi Container Pod in Kubernetes: Syntax & Example

In Kubernetes, a Pod can run multiple containers by listing them under the containers field in the Pod specification. Each container runs in the same Pod and shares the network and storage, enabling them to work closely together.
📐

Syntax

A multi container Pod is defined in a YAML file where the spec.containers field is an array listing each container. Each container has its own name, image, and optional settings like ports or environment variables.

All containers share the Pod's network and storage, allowing easy communication and data sharing.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: multi-container-pod
spec:
  containers:
  - name: container-one
    image: busybox
    command: ['sh', '-c', 'echo Hello from container one; sleep 3600']
  - name: container-two
    image: busybox
    command: ['sh', '-c', 'echo Hello from container two; sleep 3600']
💻

Example

This example shows a Pod with two containers running the busybox image. Each container prints a message and then sleeps to keep running. Both containers run inside the same Pod and share the network namespace.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: multi-container-example
spec:
  containers:
  - name: logger
    image: busybox
    command: ['sh', '-c', 'echo Logger container started; sleep 3600']
  - name: worker
    image: busybox
    command: ['sh', '-c', 'echo Worker container started; sleep 3600']
Output
kubectl get pods NAME READY STATUS RESTARTS AGE multi-container-example 2/2 Running 0 10s
⚠️

Common Pitfalls

  • Forgetting to specify unique name for each container causes errors.
  • Assuming containers run independently; they share the same Pod lifecycle and network.
  • Not setting proper resource limits can cause one container to starve others.
  • Using latest tag for images can cause unpredictable deployments.
yaml
apiVersion: v1
kind: Pod
metadata:
  name: bad-pod
spec:
  containers:
  - name: app
    image: busybox
  - name: app
    image: busybox
# This will fail because container names must be unique

---

apiVersion: v1
kind: Pod
metadata:
  name: good-pod
spec:
  containers:
  - name: app1
    image: busybox
  - name: app2
    image: busybox
📊

Quick Reference

Remember these key points when using multi container Pods:

  • Use unique container names.
  • Containers share Pod IP and storage volumes.
  • Use multi container Pods for tightly coupled containers like sidecars.
  • Manage resources carefully to avoid contention.

Key Takeaways

Define multiple containers under the spec.containers array in a Pod YAML.
Containers in the same Pod share network and storage, enabling close cooperation.
Each container must have a unique name within the Pod.
Multi container Pods are ideal for sidecar patterns and tightly coupled processes.
Avoid using the latest image tag and set resource limits to prevent conflicts.