How to add multiple containers inside a single Pod template within a k8s Deployment manifest
You can have multiple containers inside a single Pod template within a Deployment manifest. This allows you to run tightly coupled applications together. The containers within a Pod share the same network namespace and can communicate with each other using localhost
. They can also share storage volumes.
Here is an example of a Deployment manifest with multiple containers in a single Pod:
Example Deployment Manifest with Multiple Containers
apiVersion: apps/v1
kind: Deployment
metadata:
name: multi-container-deployment
spec:
replicas: 3
selector:
matchLabels:
app: multi-container-app
template:
metadata:
labels:
app: multi-container-app
spec:
containers:
- name: nginx-container
image: nginx:latest
ports:
- containerPort: 80
- name: sidecar-container
image: busybox:latest
command: ['sh', '-c', 'while true; do echo "Hello from the sidecar"; sleep 5; done']
Explanation:
- apiVersion: The version of the Kubernetes API to use.
- kind: The type of Kubernetes object. Here it is a
Deployment
. - metadata: Metadata for the Deployment, including its name.
- spec: The specification of the Deployment.
- replicas: The number of Pod replicas to run.
- selector: Specifies how to identify the Pods that belong to this Deployment using labels.
- template: The template for creating the Pods.
- metadata: Metadata for the Pods, including labels.
- spec: The specification for the Pods.
- containers: A list of containers to run in each Pod.
- name: The name of the container.
- image: The Docker image for the container.
- ports: The ports that the container exposes (optional).
- command: The command to run inside the container (optional).
- containers: A list of containers to run in each Pod.
Use Case:
- nginx-container: Runs an NGINX web server.
- sidecar-container: Runs a BusyBox container that outputs a message every 5 seconds. This could represent a sidecar container for logging, monitoring, or other auxiliary tasks.
Apply the Deployment:
-
Save the YAML to a file, for example
multi-container-deployment.yaml
. -
Apply the deployment to your Kubernetes cluster:
kubectl apply -f multi-container-deployment.yaml
-
Verify the Deployment:
kubectl get deployments
-
Inspect the Pods:
kubectl get pods
-
Check the logs of each container:
kubectl logs <pod-name> -c nginx-container kubectl logs <pod-name> -c sidecar-container
Published on: Jul 03, 2024, 06:20 AM