✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.2.11.3 USER File Ownership

A focused guide to USER File Ownership, connecting core concepts with practical Docker and container operations.

USER file ownership concerns ensuring that files a non-root user needs to read, write, or execute are actually owned by, or otherwise accessible to, that user — a necessary companion consideration to switching USER away from root, since file permissions do not automatically adjust themselves.

The Problem Switching USER Alone Doesn't Solve

Simply adding a USER instruction does not retroactively change the ownership of files that were copied into the image while still running as root; those files remain owned by root unless ownership is explicitly addressed.

COPY . /app
USER appuser
CMD ["python", "/app/app.py"]

If the application needs to write to a file or directory under /app, and those files are still owned by root, this configuration would fail at runtime due to a permissions error.

Fixing Ownership With COPY --chown

The most direct fix sets correct ownership at the moment files are copied into the image, avoiding both the permissions problem and the need for a separate cleanup instruction.

COPY --chown=appuser:appuser . /app
USER appuser
Fixing Ownership for Specific Directories Only

When only certain directories genuinely need to be writable by the non-root user — log directories, temporary file locations — ownership can be adjusted more narrowly rather than for the entire application directory.

RUN mkdir -p /app/logs && chown appuser:appuser /app/logs
USER appuser
Verifying Ownership Is Correct

After configuring ownership, confirming the running container's non-root user can actually access what it needs to is a useful verification step before considering the configuration complete.

docker run --rm myapp touch /app/logs/test.log
Why File Ownership Matters Alongside USER

Switching to a non-root user without addressing file ownership is a common source of confusing runtime permission errors — the two need to be considered together, since neither alone is sufficient for a properly functioning non-root container.