Building Images with a Dockerfile

Intermediate

Overview

A Dockerfile is a recipe. FROM picks a base image, COPY adds your files, RUN executes build steps, and CMD sets the default command when the container starts.

Each instruction creates a cached layer. Order matters: copy dependency manifests and install before copying the rest of the code so rebuilds stay fast.

docker build -t name:tag . builds the image from the Dockerfile in the current directory.

Cheatsheet

FROM node:20-alpineChoose a base image
WORKDIR /appSet the working directory
COPY package*.json ./Copy manifests first (cache)
RUN npm ciInstall dependencies
CMD ["node", "server.js"]Default start command
docker build -t app:1.0 .Build and tag the image

Try it

A safe, simulated terminal. Run the suggested commands to see typical output.

simulated terminal

Type a command and press Enter, or click a suggestion below to run it.

$

Quick quiz

1. Which instruction sets the command run when the container starts?

2. Why copy package.json before the rest of the source?