Stop 16 · Docker & ContainersTopics · 2/9

Dockerfile

Part of the Backend Developer Roadmap

In short

A Dockerfile is a short text recipe that turns your project into an image. Write it well and builds take seconds; write it carelessly and every tiny change waits for npm install.

A text file of instructions describing how to build a Docker image for your app — base image, dependencies, files to copy, and the command to run.

The blob cooks dal while following a recipe card with small step drawings pinned above the stove.

Think of it like this

The family dal recipe

A good recipe card says: start with this pot, add these ingredients in this order, cook this long. Anyone in the family follows it and gets the same dal. A Dockerfile is that card for your app, and Docker follows it line by line.

Watch it happen

Building a Node API image, step by step

FROM
WORKDIR
COPY pkg
RUN npm ci
COPY .
CMD

1/6Start from an official Node image. Your image is built on top of it.

The big ideas

What you need to know

Each line is a layer

Docker caches every step. If a step's inputs haven't changed, it's reused, so order lines from rarely to often changed.

Use .dockerignore

List node_modules, .env and .git there, so they're never copied into the build or the image.

Don't run as root

Official Node images include a node user. Switch to it with USER node before CMD.

RUN vs CMD

RUN executes while building the image. CMD is what runs each time a container starts.

See it in code

Walk through the code

dockerfile
1FROM node:22-alpine2WORKDIR /app3 4COPY package*.json ./5RUN npm ci --omit=dev6 7COPY . .8ENV NODE_ENV=production9EXPOSE 300010USER node11CMD ["node", "server.js"]

1/4Pin the base image's major version and pick a working folder.

Build it with docker build -t chai-api . and run it with docker run -p 3000:3000 chai-api. EXPOSE only documents the port; -p actually opens it.

Save yourself the pain

Common mistakes

Oops

Putting COPY . . before RUN npm ci.

Do this instead

Then every code change reinstalls all packages. Copy package files, install, then copy code.

Oops

Copying your .env into the image.

Do this instead

Images get shared and pushed. Pass secrets at run time with -e or --env-file instead.

Your mission

Containerise an old Express app

~30 min

Quick check

You changed one route file and rebuilt. Why did npm ci run again?

Go deeper

  1. 1Write a Dockerfile for a Node.js app from scratch.
  2. 2Learn common instructions: `FROM`, `WORKDIR`, `COPY`, `RUN`, `CMD`.
  3. 3Optimize layer caching by copying `package.json` and installing dependencies before copying the rest of your code.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge