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
emptyDir
volume in the pod template - The pod has two containers named writer and reader
- The
emptyDir
volume is mounted on/writer-data
directory of the writer container - The
emptyDir
volume is mounted on/reader-data
directory of the reader container - The writer container writes some data in the
my-data.txt
file every 5 seconds - The reader container reads the same data from
my-data.txt
file 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
writer
container: -
Verify if
/writer-data
directory is present in thewriter
container: -
View the content of
/writer-data/my-data.txt
file: -
Exit out of the
writer
container: -
Start a shell session inside the
reader
container: -
Verify if
/reader-data
directory is present in thereader
container: -
View the content of
/reader-data/my-data.txt
file: -
Exit out of the
reader
container: -
View
reader
container logs:
Observations:
- The content of
my-data.txt
is shared betweenwriter
andreader
containers. - Any changes made to the
my-data.txt
file in thewriter
container are immediately visible in thereader
container. - The
reader
container 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: