Tmpfs Mounts: Speed & Security

Sometimes, persistence is the enemy. When dealing with cryptographic keys, high-speed caches, or session data, writing to disk is a security risk and a performance bottleneck. Enter Tmpfs: storage that lives entirely in RAM.

1. The “Anti-Persistence” Layer

A tmpfs mount creates a temporary filesystem in the host’s memory.

  • Ephemeral: When the container stops, the data vanishes instantly.
  • Secure: Data is never written to the host’s physical disk (unless swap is used).
  • Fast: Read/Write speeds are limited only by RAM bandwidth (GB/s), not Disk I/O.

2. Use Cases

1. Secrets Management

Mounting a directory as tmpfs ensures that sensitive files (like private_key.pem) are never committed to the container layer or leaked to the host disk.

2. High-Performance Caching

For applications that compile code on the fly or process massive streams, standard disk I/O (even SSDs) can be too slow. RAM is orders of magnitude faster.

[!WARNING] Capacity Limits: Since tmpfs uses RAM, filling it up can cause the host to run out of memory (OOM). Always set a size limit (e.g., --tmpfs /app/cache:size=512m).


3. Interactive: Latency Simulator

Visualize the difference between writing to Disk (Overlay2) vs RAM (Tmpfs).

💾 Overlay2 (Disk)
0 ms
Tmpfs (RAM)
0 ms
Ready to benchmark...

4. Code Example: Using Tmpfs

# Mount a 100MB tmpfs at /app/cache
docker run -d \
  --tmpfs /app/cache:rw,size=100m,mode=1777 \
  my-app
version: '3.8'
services:
  web:
    image: nginx
    tmpfs:
      - /run
      - /tmp
package main

import (
    "fmt"
    "os"
    "time"
)

func main() {
    // /app/cache is mounted as tmpfs
    cacheFile := "/app/cache/session_123.dat"

    start := time.Now()

    // Write sensitive data
    data := []byte("SECRET_SESSION_TOKEN_XYZ")
    err := os.WriteFile(cacheFile, data, 0600)
    if err != nil {
        panic(err)
    }

    duration := time.Since(start)
    fmt.Printf("Wrote secret to RAM in %v\n", duration)

    // Verify it's not on disk by checking mount type (Linux only)
    // In production, you'd check /proc/mounts
}