🐳Docker Learning Hub
Lesson 12 • Dockerfile best practices
Lesson 12

Dockerfile best practices

This page focuses on writing Dockerfiles that are clean, stable, cache-friendly, and safer for long-term project work.

Main idea

A Dockerfile should not only work once. It should also be easy to understand and easy to maintain later.

Good habits

Pick base images intentionally, use stable versions, use `WORKDIR`, support caching, and keep startup commands clear.

Bad habits

Using `latest`, copying everything too early, or storing secrets in Dockerfiles creates future problems.

Clean example

FROM node:18-alpine WORKDIR /app COPY package.json . RUN npm install COPY server.js . EXPOSE 3000 CMD ["npm", "start"]

Why it is better

  • Stable base image instead of `latest`
  • Clear working directory
  • Better layer caching
  • Readable startup command

Best practice checklist

Choose base image intentionally
Be specific with versions whenever stability matters.
Support caching
Copy dependency files before changing source files when possible.
Keep Dockerfile readable
Use logical order, clear paths, and understandable startup commands.
Avoid unsafe shortcuts
Do not bake secrets or unnecessary tools into the image.

Next page: Lesson 13 compares bind mounts and volumes for development and persistent storage use cases.