Docker Fundamentals

Lesson 3 of 6

Writing a Dockerfile

A Dockerfile is a script that describes how to build your own image, step by step.

FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 3000
CMD ["node", "server.js"]

Reading it line by line

  • FROM picks a base image to start from, here a lightweight Node.js image.
  • WORKDIR sets the working directory inside the container for every instruction after it.
  • COPY copies files from your machine into the image.
  • RUN executes a command while building the image (installing dependencies, here).
  • EXPOSE documents which port the container listens on.
  • CMD is the command that runs when a container starts from this image.

Building and running your image

docker build -t my-app .
docker run -p 3000:3000 my-app

-t my-app tags the image with a name so you can refer to it later instead of a random id.

WARNING

Copying package*.json and running npm install before copying the rest of your code lets Docker reuse that cached layer when only your source changes, skipping a slow reinstall on every build.

📝 Dockerfile Quiz

Passing score: 70%
  1. 1.Which Dockerfile instruction runs a command while the image is being built (like installing dependencies)?

  2. 2.The docker ____ -t my-app . command builds an image from a Dockerfile and tags it "my-app".

  3. 3.CMD specifies the command that runs when a container starts, not while the image is built.