Module 3 Lesson 4: Dockerfile Best Practices
·DevOps

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), use FROM node:18-alpine (~150MB).
  • Clean up after yourself: If you install a package, delete the cache in the same RUN command.
    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:

  • .env files (containing API keys)
  • .aws or .ssh credentials
  • Local database files
  • node_modules (which should be installed inside the container, not copied from your laptop).

5. Summary Checklist

Best PracticeWhy?
Use Slim BasesSmaller size / Faster deploys
Combine RUNsFewer layers / Smaller footprint
Use WORKDIRClear folder structure
Add a non-root USERsecurity (Principle of Least Privilege)
Use tags, not 'latest'Predictability (avoid breaking builds)

Exercise: The Security Audit

  1. Open an open-source project on GitHub and find their Dockerfile.
  2. Count how many RUN commands they have. Can any be combined?
  3. Do they use a USER instruction, or are they running as Root?
  4. 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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn