🐳 Docker Learning Hub
Lesson 11 • Docker image optimization
Lesson 11

Docker image optimization

This page focuses on making images smaller, faster to build, easier to transfer, and cleaner for real project use.

Main goal

A good image should work well without carrying extra files, tools, or unnecessary weight.

Main benefits

Smaller images usually mean faster builds, faster downloads, quicker deployments, and easier maintenance.

Main warning

Optimization should improve clarity and efficiency, not make the Dockerfile confusing too early.

Use a smaller base image

FROM node:18 # smaller option FROM node:18-alpine

Smaller base images often reduce image size and download time, as long as they still fit your app needs.

Use `.dockerignore`

node_modules .git .env dist coverage npm-debug.log

This prevents unnecessary files from being sent into the Docker build context.

Bad copy habit

COPY . /app
May include extra files
Bigger image

Better copy habit

Copy only needed files first
Use `.dockerignore`
Cleaner image

Cache-friendly Dockerfile order

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

Copy dependency files first so Docker can reuse cached install layers when app code changes later.

Why order matters

If you copy the whole project before dependency installation, even a small file change may force Docker to reinstall everything again.

Keep runtime images clean

  • Install only necessary packages.
  • Avoid editors and debug tools in production images.
  • Keep the final image focused on runtime needs.

Multi-stage builds

FROM node:18 AS builder # build steps FROM node:18-alpine # copy only final output

One stage builds the app, the final stage keeps only what is needed to run it.

Optimization checklist

Use a suitable base image
Prefer smaller images when they still work well for your app.
Add `.dockerignore`
Stop unnecessary files from entering the build context.
Order Dockerfile instructions wisely
This helps Docker caching work better.
Keep the image focused
Include runtime needs, not extra build or debug clutter.

Next page: Lesson 12 focuses on Dockerfile best practices so you can write cleaner and more professional Docker build files.