On-disk files in a container are ephemeral, which presents some problems for non-trivial applications when running in containers. One problem is the loss of files when a container crashes. The kubelet restarts the container but with a clean state. A second problem occurs when sharing files between containers running together in a Pod. The Kubernetes volume abstraction solves both of these problems. Familiarity with Pods is suggested

EmptyDir Volume

  • An emptyDir volume is first created when a Pod is assigned to a Node and initially its empty
  • A Volume of type emptyDir that lasts for the life of the Pod, even if the Container terminates and restarts.
  • If a container in a Pod crashes the emptyDir content is unaffected.
  • All containers in a Pod share use of the emptyDir volume.
  • Each container can independently mount the emptyDir at the same / or different path.
  • Using emptyDir, The Kubelet will create the directory in the container, but not mount any storage.
  • Containers in the Pod can all read/write the same files in the emptyDir volume, though that volume can be mounted at the same or different paths in each Container.
  • When a Pod is removed from a node for any reason, the data in the emptyDir is deleted forever along with the container.
  • A Container crashing does NOT remove a Pod from a node, so the data in an emptyDir volume is safe across Container crashes.
  • By default, emptyDir volumes are stored on whatever medium is backing the node – that might be disk or SSD or network storage.
  • You can set the emptyDir.medium field to “Memory” to tell Kubernetes to mount a tmpfs (RAM-backed filesystem) for you instead.
  • The location should of emptyDir should be in /var/lib/kubelet/pods/{podid}/volumes/kubernetes.io~empty-dir/ on the given node where your pod is running.

Some uses for an emptyDir are:

  • scratch space, such as for a disk-based merge sort
  • checkpointing a long computation for recovery from crashes
  • holding files that a content-manager container fetches while a webserver Container serves the data

EmptyDir example

vim emptydirvolume.yaml

apiVersion: v1
kind: Pod
  name: test-vol1
   - image: coolgourav147/nginx-custom
     name: test-container
	    - mountPath: /data
		  name: first-volume
     - name: first-volume
	   emptyDir: {}

kubectl apply -f emptydirvolume.yaml

above command will create one pod and inside which we will have a volume attached inside /data folder

Now execute the container and make some files inside /data folder

After making changes terminate the container or stop the process

Now the pod will be recreated, again execute the newly created pod, you can see the files created in the earlier pod in this pod too.