Docker "cache mount permission denied (--mount=type=cache)" in CI
A --mount=type=cache directory is created with default ownership (root) unless told otherwise. When the build runs as a non-root USER, writes into that cache path are denied because the mounted directory is not owned by the build user.
What this error means
A build step using a cache mount fails with permission denied when it writes into the cache directory. The Dockerfile switched to a non-root user before the cached RUN.
ERROR: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1
# Could not install packages: [Errno 13] Permission denied: '/root/.cache/pip'Common causes
The cache mount is owned by root
By default the cache directory is root-owned; a non-root build user cannot write into it.
uid/gid not set on the mount
Without uid=/gid= on the mount, BuildKit does not align the cache ownership with the active USER.
How to fix it
Set uid/gid (and mode) on the cache mount
- Pass
uidandgidmatching the build user so the cache is writable. - Set
mode=0755if you need a specific permission.
RUN --mount=type=cache,target=/home/app/.cache,uid=1000,gid=1000 \
pip install --cache-dir /home/app/.cache -r requirements.txtPoint the cache at a user-writable path
- Target the cache at a directory the non-root user owns.
- Set the cache directory env so the tool uses it.
USER app
ENV PIP_CACHE_DIR=/home/app/.cache/pip
RUN --mount=type=cache,target=/home/app/.cache/pip,uid=1000,gid=1000 \
pip install -r requirements.txtHow to prevent it
- Set uid/gid on cache mounts when building as non-root.
- Point tool cache dirs at user-owned paths.
- Keep the USER and the cache ownership aligned.