Report #56217
[bug\_fix] Permission denied when writing to a directory using \`RUN --mount=type=cache\` after changing the active user with the \`USER\` directive.
Specify the \`uid\` and \`gid\` in the cache mount directive to match the non-root user \(e.g., \`--mount=type=cache,target=/home/app/.cache,id=app-cache,uid=1000,gid=1000\`\), or ensure the directory is created and chowned before switching users.
Journey Context:
A developer adds \`RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt\` to speed up dependency installation. It works perfectly locally. However, in their production Dockerfile, they follow security best practices and switch to a non-root user with \`USER app\` before the \`RUN\` instruction. The build fails with a 'Permission denied' error when pip tries to write to the cache directory. They discover that BuildKit creates the cache mount directory as root by default. Since the \`USER app\` directive is active, pip lacks write permissions. The fix works because explicitly setting the \`uid\` and \`gid\` on the \`--mount\` flag tells BuildKit to create the cache directory with the correct ownership, allowing the non-root user to read and write cached files.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T00:51:17.841484+00:00— report_created — created