Sharing Data Between Containers in a Kubernetes Pod Using Volumes
In Kubernetes, Pods often contain multiple containers working together. While each container has its file system, sometimes they need to share data. This is where volumes come in, providing a persistent storage layer accessible by all containers within the Pod.
In this KodeKloud task, we'll follow the imperative approach, first creating the Pod without volume functionality and then editing it to incorporate volume sharing.
kubectl run volume-share-nautilus --image=ubuntu-latest --restart=Never --dry-run=client -o yaml -- sleep 10000
This YAML defines a Pod named volume-share-nautilus with a container running on ubuntu-latest as an image and instructed to sleep for 10000 seconds. The restartPolicy is set to Never to ensure the Pod doesn't automatically restart upon termination.
Adding Volume Functionality:
To enable data sharing, we need to modify the Pod YAML to include a volume and volume mounts:
领英推荐
apiVersion: v1
kind: Pod
metadata:
name: volume-share-nautilus
spec:
volumes:
- name: volume-share
emptyDir: {}
containers:
- command:
- sleep
- "10000"
image: ubuntu:latest
name: volume-container-nautilus-1
volumeMounts:
- name: volume-share
mountPath: /tmp/official
- command:
- sleep
- "10000"
image: ubuntu:latest
name: volume-container-nautilus-2
volumeMounts:
- name: volume-share
mountPath: /tmp/games
dnsPolicy: ClusterFirst
restartPolicy: Never
volumes: This section defines a volume named volume-share. We're using the emptyDir type, which creates a temporary directory within the Pod that persists as long as the Pod is running.
volumeMounts: Within each container definition, we specify the volumeMounts section. This maps the volume-share volume to a specific path within the container's file system. The containers mount the volume at /tmp/games and /tmp/official respectively
Verify the Shared Volume
We are going to SSH into the containers and verify if we have the directories. We will be using kubectl exec volume-share-nautilus -c volume-container-nautilus-1 create a file inside /tmp/official/ and verify the same file in the other container