Module 3 Lesson 4: Dockerfile Best Practices
Build production-grade images. Learn how to minimize image size, enhance security, and ensure maintainability in your Docker configurations.
Module 3 Lesson 4: Dockerfile Best Practices
Writing a Dockerfile is easy. Writing a Production-Ready Dockerfile requires a few professional habits. Following these tips will make your images smaller, safer, and faster.
1. Keep Images Minimal
Smaller images download faster and have a "Smaller Attack Surface" for hackers.
- Use "Alphine" or "Slim" variants: Instead of
FROM node:18(which is ~1GB), useFROM node:18-alpine(~150MB). - Clean up after yourself: If you install a package, delete the cache in the same
RUNcommand.RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
2. Leverage Layer Sharing (Combine Commands)
Every RUN command creates a new layer. To avoid "Layer Bloat," combine related commands into one.
- Bad:
RUN apt-get update RUN apt-get install -y python3 RUN apt-get install -y wget - Good:
RUN apt-get update && apt-get install -y \ python3 \ wget && \ rm -rf /var/lib/apt/lists/*
3. Don't Run as Root (The Security Pillar)
By default, Docker containers run as the "Root" (Administrator) user. If a hacker escapes your app, they have full control over the container.
- The Fix: Create a generic user and switch to them at the end of the Dockerfile.
RUN groupadd -r myuser && useradd -r -g myuser myuser USER myuser
4. Use .dockerignore Religiously
If you don't have a .dockerignore file, you might accidentally copy sensitive things into your public image:
.envfiles (containing API keys).awsor.sshcredentials- Local database files
node_modules(which should be installed inside the container, not copied from your laptop).
5. Summary Checklist
| Best Practice | Why? |
|---|---|
| Use Slim Bases | Smaller size / Faster deploys |
| Combine RUNs | Fewer layers / Smaller footprint |
| Use WORKDIR | Clear folder structure |
| Add a non-root USER | security (Principle of Least Privilege) |
| Use tags, not 'latest' | Predictability (avoid breaking builds) |
Exercise: The Security Audit
- Open an open-source project on GitHub and find their
Dockerfile. - Count how many
RUNcommands they have. Can any be combined? - Do they use a
USERinstruction, or are they running as Root? - Check their
.dockerignore. Are they excluding their local environment files?
Summary
A professional Dockerfile is surgical. It includes exactly what is needed—no more, no less. By sticking to these best practices, you ensure that your applications are not just "Containerized," but "Enterprise-Ready."
Next Lesson: Naming and organizing: Image tagging and versioning.