📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Docker Dockerfile Best Practices

Dockerfile Best Practices

5 min read Quiz at the end
Write lean cache-friendly Dockerfiles using layer ordering, .dockerignore, and non-root users.

Dockerfile Best Practices

# 1. Pin specific image tags
FROM python:3.12-slim

# 2. Dependency files before source (cache layer)
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

# 3. Combine RUN steps to reduce layers
RUN apt-get update     && apt-get install -y curl     && rm -rf /var/lib/apt/lists/*

# 4. .dockerignore
# node_modules
# .git
# .env

# 5. Non-root user
RUN adduser --disabled-password appuser
USER appuser
Topic Quiz · 2 questions

Test your understanding before moving on

1. Why should dependency files be copied before source code in a Dockerfile?
💡 Copying package.json before source means dependency layers are cached until requirements change.
2. What is the purpose of a .dockerignore file?
💡 .dockerignore prevents large or sensitive files from being sent to the Docker daemon during build.