Docker & Containerization: Scenario-Based Questions
3. A Docker image build fails with a "permission denied" error on a RUN command. How would you debug and fix this?
"Permission denied" errors during Docker builds usually stem from file ownership issues, incorrect user contexts, or misconfigured Dockerfile instructions. Understanding how the image layers are built is key.
🔍 Diagnostic Approach
- Review the Failing Command: Examine the exact
RUN
step triggering the error and what file/directory it accesses. - Check User Context: Docker may be running the command as a non-root user depending on base image (
node
,python
, etc.). - Inspect File Permissions: Validate using
ls -la
if files are accessible by the current user inside the container. - Use Debugging Shell: Build an intermediate image with
/bin/bash
as entrypoint and exec into it to test manually.
🛠 Common Causes
- Non-root Base Image: Some base images use a non-root user by default (e.g.,
node:alpine
). - Copying Files with Host Permissions: Files copied from the host may not be accessible without changing ownership inside the container.
- Incorrect File Paths: File not present or incorrectly named at the time of the
RUN
command.
🧪 Troubleshooting Techniques
- Insert a debugging step before the failure:
RUN ls -la /path/to/file && whoami
- Switch to root for that layer if necessary:
USER root
- Fix file ownership explicitly:
RUN chown -R appuser:appuser /app
✅ Resolution Patterns
- Ensure correct user is set for each build step using
USER
. - Always verify
COPY
andADD
targets match actual context paths. - Use multi-stage builds to separate privileged operations from final image logic.
🚫 Pitfalls to Avoid
- Blindly adding
chmod 777
— creates security issues. - Forgetting
WORKDIR
context before running file-dependent commands. - Not validating intermediate container states with
docker run -it
.
📌 Real-World Insight
In production pipelines, “permission denied” errors during container builds can stall CI/CD. Using consistent user management, debugging images interactively, and structuring Dockerfiles with layered context can eliminate most of these issues early.