0
0
DockerHow-ToBeginner · 3 min read

How to Use tmpfs Mount in Docker for In-Memory Storage

Use the --tmpfs flag in docker run to mount a temporary file system (tmpfs) inside a container. This creates a fast, in-memory storage that is cleared when the container stops, ideal for sensitive or temporary data.
📐

Syntax

The basic syntax to use a tmpfs mount in Docker is:

docker run --tmpfs <container_path>[:options] <image>

Here:

  • <container_path> is the directory inside the container where tmpfs will be mounted.
  • options are optional settings like size or mode (permissions).
  • <image> is the Docker image you want to run.
bash
docker run --tmpfs /app/tmp:rw,size=64m myimage
💻

Example

This example runs an Alpine Linux container with a tmpfs mount at /tmpfs limited to 100 MB. It shows how to create a file inside the tmpfs and list it.

bash
docker run --rm --tmpfs /tmpfs:rw,size=100m alpine sh -c "echo 'Hello tmpfs' > /tmpfs/hello.txt && cat /tmpfs/hello.txt"
Output
Hello tmpfs
⚠️

Common Pitfalls

  • Forgetting to specify size: Without size, tmpfs uses default system limits which might be too small or large.
  • Using tmpfs for persistent data: tmpfs is temporary and data is lost when the container stops.
  • Incorrect permissions: Not setting mode can cause permission issues inside the container.

Example of wrong and right usage:

bash
# Wrong: no size specified

docker run --tmpfs /cache alpine ls /cache

# Right: specify size and read-write mode

docker run --tmpfs /cache:rw,size=50m alpine ls /cache
📊

Quick Reference

Here is a quick cheat-sheet for tmpfs mount options:

OptionDescriptionExample
sizeMaximum size of tmpfs (e.g., 100m for 100 megabytes)size=100m
modePermissions in octal (e.g., 1777 for sticky bit)mode=1777
rw/roMount as read-write or read-onlyrw or ro
noexecDo not allow execution of binariesnoexec
nosuidIgnore set-user-identifier or set-group-identifier bitsnosuid

Key Takeaways

Use --tmpfs in docker run to mount fast, in-memory storage inside containers.
Always specify size to control memory usage of tmpfs mounts.
tmpfs data is temporary and lost when the container stops.
Set appropriate permissions with mode option to avoid access issues.
tmpfs is ideal for sensitive or temporary files that don't need persistence.