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.
- Updated Nov 27, 2026
- Markdown
Package a small Node.js app into an image with a Dockerfile and run it.
- 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.
- First
docker build -t hello-node .: every step runs.FROMpulls the base image,RUN npm installexecutes, and each result is stored as a layer. - Run the same command again with no changes: every step reports that it is cached, and the build ends in a moment.
- Edit
server.jsand build again:FROM,WORKDIR, thepackage.jsoncopy andnpm installare still cached. OnlyCOPY . .and what follows run again. - Edit
package.jsoninstead: the install layer is invalid, sonpm installruns 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:
require("http").createServer((req, res) => res.end("Hello from Docker\n")).listen(3000);And package.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):
FROM node:22-alpine
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]FROMpicks the base image. Thealpinevariant is small and uses musl instead of glibc.WORKDIRsets the folder inside the image and creates it if missing.COPYcopies files from the build context into the image.RUNruns a command at build time and keeps the result as a layer.CMDis 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:
node_modules
.git
*.log
.envWithout 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#
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#
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#
curl http://localhost:3000
docker pscurl 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.1is 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 . .beforeRUN npm installreinstalls dependencies on every code change. Copy the dependency files first. - A huge build context is slow. Without
.dockerignore, Docker uploads.gitandnode_moduleson every build. Ignore them. - EXPOSE does not publish. It is documentation. You still need
-por Composeports(see Publish container ports safely). - Shell form hides signals.
CMD npm start(no brackets) runs through/bin/sh -c, sodocker stopmay wait for the full grace period before killing it. Prefer the bracket form. - Images run as root by default. Official Node images include a
nodeuser. AddingUSER nodeafter 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#
| Symptom | Likely cause | Fix |
|---|---|---|
COPY failed: file not found | The file is outside the build context or in .dockerignore | Move it inside the folder, or remove the ignore line |
failed to read dockerfile | No file named Dockerfile in the folder you passed | Run the build in the right folder, or use -f |
Bind for 127.0.0.1:3000 failed: port is already allocated | Another process uses that host port | Pick another, such as -p 127.0.0.1:3001:3000 |
| Container exits at once | The start command failed | docker logs hello and read the error |
curl: (52) Empty reply or connection reset | The app listens only on 127.0.0.1 inside the container | Bind to 0.0.0.0 |
| Rebuild reinstalls everything | COPY . . comes before the install step | Reorder so dependency files are copied first |
exec format error on the server | Image built for a different CPU architecture | Build with --platform for the server |
| The image is very large | Build tools and dev dependencies stay in the final image | Use a multi-stage build and a small base |
| Build is slow on every run | COPY . . comes before the install, the context is huge, or --no-cache is set | Reorder, add .dockerignore, drop --no-cache |
App cannot write files after adding USER node | The target folder is owned by root | COPY --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#
| Instruction | What it does |
|---|---|
FROM node:22-alpine | Choose the base image |
WORKDIR /app | Set and create the working folder |
COPY src dest | Copy files from the build context |
RUN cmd | Run a command at build time (new layer) |
ENV NAME=value | Set 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
COPYsecrets such as.envor 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.
Related lessons#
- Multi-stage Docker builds: smaller final images
- Image, container and registry explained: share the image you built
- Docker networks explained: connect your app to a database
- Environment variables and secrets: keep secrets out of the image
Next#
Connect your containers with Docker networks explained.
Check what you learned
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
Keep going: guides and tutorials
- Deploy a Docker Compose App Self-Hosted: Web, Redis and Rollback Deploy a Docker Compose app on your own server with Levelrail: a web service and Redis, a bad release that does not take traffic, and a compose rollback.
- Docker Container Restarting in a Loop: 5 Causes, Fixed Five real reasons a Docker container keeps restarting, each reproduced with its exit code, the command that finds it and the fix. Then the same crash on Levelrail.
- Deploy an Express App to a VPS With Docker and Health Checks Deploy a Node.js Express API to your own server with no Dockerfile. Covers the port rule, a health route, secrets, deploy failure codes and rollback.