Chapter 2 · Lesson 5 of 20
Docker

Write your first Dockerfile and build an image with docker build

A Dockerfile is a text file of instructions that tells Docker how to build an image for your app.

By the end you will

Package a small Node.js app into an image with a Dockerfile and run it.

Time
22 min
Level
Beginner
Check
4 questions
You need
  • Docker installed

A Dockerfile is a text file of build instructions: start FROM a base image, copy your files in, run install commands, and set the command to start. You turn it into an image with docker build -t NAME . and start containers from that image with docker run.

How it works#

docker build reads the Dockerfile from top to bottom. Most instructions (FROM, COPY, RUN) each produce a layer: a saved set of file changes. The image is those layers stacked, and CMD records what to start.

Layers are cached. If an instruction and everything before it are unchanged since the last build, Docker reuses the saved layer instead of running it again. The moment one layer changes, every layer after it is rebuilt. That is why you copy package.json and run npm install before copying the rest of the code: a code-only edit then reuses the slow install layer.

The build context is the folder you pass to docker build (the final .). Docker sends it to the builder, and COPY can only see files inside it. A .dockerignore file removes things from the context, which makes builds faster and stops secrets and node_modules from leaking in.

This lesson uses a tiny Node.js app. The same ideas work for Python or any other language.

A worked example, start to finish#

Build the image from the steps below twice and watch the cache.

  1. First docker build -t hello-node .: every step runs. FROM pulls the base image, RUN npm install executes, and each result is stored as a layer.
  2. Run the same command again with no changes: every step reports that it is cached, and the build ends in a moment.
  3. Edit server.js and build again: FROM, WORKDIR, the package.json copy and npm install are still cached. Only COPY . . and what follows run again.
  4. Edit package.json instead: the install layer is invalid, so npm install runs again, and so does everything after it.

That is the whole reason for the odd-looking order of COPY lines: put what changes rarely first and what changes often last.

Step 1: Create the app#

Make a folder with two files. server.js:

js
require("http").createServer((req, res) => res.end("Hello from Docker\n")).listen(3000);

And package.json:

json
{ "name": "hello", "version": "1.0.0", "scripts": { "start": "node server.js" } }

listen(3000) with no host listens on all addresses, which is what a container needs.

Step 2: Write the Dockerfile#

Create a file named Dockerfile (no extension):

dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]
  • FROM picks the base image. The alpine variant is small and uses musl instead of glibc.
  • WORKDIR sets the folder inside the image and creates it if missing.
  • COPY copies files from the build context into the image.
  • RUN runs a command at build time and keeps the result as a layer.
  • CMD is the command a container runs when it starts. The square-bracket (exec) form runs the program directly, so it receives stop signals properly.

Step 3: Add a .dockerignore#

Create .dockerignore so local junk is not copied into the image:

output
node_modules
.git
*.log
.env

Without it, COPY . . would also copy your local node_modules (possibly built for a different OS) and any secrets in .env.

Step 4: Build the image#

bash
docker build -t hello-node .

-t names (tags) the image. The dot is the build context. Add a version such as -t hello-node:1.0 to keep builds apart. To share the image, see Image, container and registry explained.

What you should see: step lines for each instruction, then a message that the image was built or named hello-node. Run it again with no changes and the steps finish almost instantly, because they come from cache.

Step 5: Run it#

bash
docker run -d --name hello -p 127.0.0.1:3000:3000 hello-node

-p host:container publishes a port. Written as -p 3000:3000 it is exposed on all interfaces of the machine, so anyone who can reach the host can reach the app. Binding to 127.0.0.1 keeps it local.

What you should see: a container ID.

Check it worked#

bash
curl http://localhost:3000
docker ps

curl prints Hello from Docker, and docker ps lists hello as Up. If it exited, docker logs hello shows the error. Now edit server.js, run docker build -t hello-node . again, and watch the npm install step reuse the cache while the final copy step reruns.

Edge cases and gotchas#

  • The app must listen on 0.0.0.0. Inside a container, 127.0.0.1 is private to that container. A published port reaches the container’s network interface, so an app bound to loopback looks dead from outside. Check your framework’s host setting.
  • Instruction order controls cache. Putting COPY . . before RUN npm install reinstalls dependencies on every code change. Copy the dependency files first.
  • A huge build context is slow. Without .dockerignore, Docker uploads .git and node_modules on every build. Ignore them.
  • EXPOSE does not publish. It is documentation. You still need -p or Compose ports (see Publish container ports safely).
  • Shell form hides signals. CMD npm start (no brackets) runs through /bin/sh -c, so docker stop may wait for the full grace period before killing it. Prefer the bracket form.
  • Images run as root by default. Official Node images include a node user. Adding USER node after the install steps limits damage if the app is compromised, but check that files you need are readable by it.
  • ARM versus amd64. An image built on Apple silicon is arm64, and may not run on an amd64 server. Build for the target with docker buildx build --platform linux/amd64.

Troubleshooting#

SymptomLikely causeFix
COPY failed: file not foundThe file is outside the build context or in .dockerignoreMove it inside the folder, or remove the ignore line
failed to read dockerfileNo file named Dockerfile in the folder you passedRun the build in the right folder, or use -f
Bind for 127.0.0.1:3000 failed: port is already allocatedAnother process uses that host portPick another, such as -p 127.0.0.1:3001:3000
Container exits at onceThe start command faileddocker logs hello and read the error
curl: (52) Empty reply or connection resetThe app listens only on 127.0.0.1 inside the containerBind to 0.0.0.0
Rebuild reinstalls everythingCOPY . . comes before the install stepReorder so dependency files are copied first
exec format error on the serverImage built for a different CPU architectureBuild with --platform for the server
The image is very largeBuild tools and dev dependencies stay in the final imageUse a multi-stage build and a small base
Build is slow on every runCOPY . . comes before the install, the context is huge, or --no-cache is setReorder, add .dockerignore, drop --no-cache
App cannot write files after adding USER nodeThe target folder is owned by rootCOPY --chown=node:node or chown before USER

Real-world scenario#

You have a small Node API that runs fine on your laptop. A colleague tries it and gets a different Node version and a missing native module. You add the Dockerfile from this lesson plus a .dockerignore, build once, and share the image through a registry. The colleague runs docker run -p 127.0.0.1:3000:3000 hello-node and gets the same behaviour you see.

A week later the image is far larger than it needs to be because the build tools came along. You split the Dockerfile into a build stage and a runtime stage, as described in Multi-stage Docker builds, and the final image shrinks. The Dockerfile stays in git next to the code, so every deploy builds from a known recipe. For a full path to a server see the blog guide Deploy an Express app with Docker on a VPS.

Quick reference#

InstructionWhat it does
FROM node:22-alpineChoose the base image
WORKDIR /appSet and create the working folder
COPY src destCopy files from the build context
RUN cmdRun a command at build time (new layer)
ENV NAME=valueSet an environment variable in the image
CMD ["prog", "arg"]Default start command, exec form
docker build -t name:tag .Build from the current folder
docker build --no-cache -t name .Ignore the cache once

Security and safety notes#

  • Never COPY secrets such as .env or private keys into an image (see Environment variables and secrets). Anyone who can pull the image can read them, and deleting the file in a later layer does not remove it from earlier layers.

Next#

Connect your containers with Docker networks explained.

Check what you learned4 questions
1Why does the Dockerfile copy package.json before copying the rest of the code?
2What is the difference between RUN and CMD?
3What does the dot in docker build -t hello-node . mean?
4Your app inside the container listens on 127.0.0.1:3000 and -p 3000:3000 is set. What happens?

Frequently asked questions

Why copy package.json before the rest of the code?

Docker caches each step. If package.json has not changed, the npm install step is reused, so rebuilds after a code edit are much faster.

What is the difference between RUN and CMD?

RUN executes while the image is being built. CMD sets the command that runs when a container starts from the image.

Does EXPOSE publish the port?

No. EXPOSE only documents which port the app uses. You still need -p, or ports in Compose, to reach it from outside.

My app works locally but not in the container. Why?

A common cause is the app listening on 127.0.0.1 only. Inside a container that address is private to the container, so listen on 0.0.0.0 instead.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios