Using emptyDir Volume to Share Data Between Containers¶
Let's see how we can use emptyDir volume to share data between containers.
Here is the Docker Image used in this tutorial: reyanshkharga/nginx
Step 1: Create a Deployment With emptyDir Volume¶
Let's create a deployment as follows:
Observe the following:
- We have added an
emptyDirvolume in the pod template - The pod has two containers named writer and reader
- The
emptyDirvolume is mounted on/writer-datadirectory of the writer container - The
emptyDirvolume is mounted on/reader-datadirectory of the reader container - The writer container writes some data in the
my-data.txtfile every 5 seconds - The reader container reads the same data from
my-data.txtfile every 5 seconds
You might wonder why the contents of the /writer-data/my-data.txt and /reader-data/my-data.txt files are the same.
The reason is that the my-data.txt file is stored in the shared my-volume volume, which is mounted to both containers on different directories. So any changes made to the file in one container are immediately visible in the other container, since they are both accessing the same file in the shared volume.
Apply the manifest to create the deployment:
Step 2: Verify Deployment and Pods¶
Let's verify if the emptyDir volume was mounted in both the containers.
-
Start a shell session inside the
writercontainer: -
Verify if
/writer-datadirectory is present in thewritercontainer: -
View the content of
/writer-data/my-data.txtfile: -
Exit out of the
writercontainer: -
Start a shell session inside the
readercontainer: -
Verify if
/reader-datadirectory is present in thereadercontainer: -
View the content of
/reader-data/my-data.txtfile: -
Exit out of the
readercontainer: -
View
readercontainer logs:
Observations:
- The content of
my-data.txtis shared betweenwriterandreadercontainers. - Any changes made to the
my-data.txtfile in thewritercontainer are immediately visible in thereadercontainer. - The
readercontainer is able to read the shared data. (Verified by checking reader container logs)
Note
The busybox image doesn't have bash so we have used sh instead to start a shell session inside reader container that uses the busybox image.
Clean Up¶
Assuming your folder structure looks like the one below:
Let's delete all the resources we created: