tmpfs mounts in a Dockerfile RUN step are a powerful way to manage temporary data during the build process, but they’re often misunderstood and misused.

Let’s see it in action. Imagine you’re building a Go application. You need to download dependencies, compile your code, and then clean up any build artifacts.

FROM golang:1.21-alpine AS builder

# Create a tmpfs mount for /app/build
RUN --mount=type=tmpfs,target=/app/build \
    cd /app && \
    mkdir -p build && \
    echo "Building application..." > build/status.log && \
    # Simulate downloading dependencies and compiling
    sleep 2 && \
    echo "Dependencies downloaded." >> build/status.log && \
    sleep 2 && \
    echo "Compilation complete." >> build/status.log && \
    echo "Build artifacts generated." >> build/status.log

FROM alpine:latest
COPY --from=builder /app/build /app/built_app
CMD ["ls", "/app/built_app"]

When you build this image (docker build -t my-go-app .), you’ll see the RUN step execute. Notice that the build directory is created within the RUN instruction, data is written to build/status.log, and then these artifacts are copied to the final image. The key here is that /app/build is a tmpfs mount.

The problem this solves is that build environments can become cluttered with temporary files that are only needed during the build and shouldn’t be part of the final image. Traditional methods involve RUN rm -rf ... commands, which are inefficient and can sometimes leave behind cruft. tmpfs provides a clean, isolated, and ephemeral filesystem for these operations.

Internally, when Docker encounters RUN --mount=type=tmpfs,target=/app/build, it creates an in-memory filesystem at /app/build specifically for that RUN instruction. This filesystem is volatile: anything written to it is lost when the RUN command finishes. This is distinct from the main build layer filesystem. The COPY --from=builder then pulls the resulting files from this temporary location into the next build stage.

The primary lever you control is the target path, which specifies where the tmpfs mount will be available within the RUN command’s execution environment. You can have multiple tmpfs mounts within a single RUN instruction by adding more --mount flags. For example, RUN --mount=type=tmpfs,target=/tmp --mount=type=tmpfs,target=/build ....

The tmpfs mount is not a persistent volume that survives the build. It’s entirely scoped to the single RUN instruction it’s declared in. This isolation is its strength, preventing accidental data leakage between build stages or into the final image.

The next concept you’ll likely explore is using tmpfs mounts for secrets during a build, where you mount a temporary location to securely copy sensitive files into a build stage without writing them to intermediate layers.

Want structured learning?

Take the full Buildkit course →