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.optionsare 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 myimageExample
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 /cacheQuick Reference
Here is a quick cheat-sheet for tmpfs mount options:
| Option | Description | Example |
|---|---|---|
| size | Maximum size of tmpfs (e.g., 100m for 100 megabytes) | size=100m |
| mode | Permissions in octal (e.g., 1777 for sticky bit) | mode=1777 |
| rw/ro | Mount as read-write or read-only | rw or ro |
| noexec | Do not allow execution of binaries | noexec |
| nosuid | Ignore set-user-identifier or set-group-identifier bits | nosuid |
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.