Skip to main content

Containers and Kubernetes · Beginner · 14 min

How to Write a Dockerfile for a Node.js App

By Padding · Updated 15 Nov 2026
Docker Engine 29 · Node.js 26

You will write a Dockerfile for a small Express app on Node.js 26, build it into an image, run it as a container on port 3000 as a non-root user, and order the file so rebuilds take seconds.

On this page

A Dockerfile is a recipe for an image: a sealed copy of your app, its runtime and its dependencies. Anyone with Docker can run that image and get the same result, on your laptop, on a server or in CI. That repeatability is the reason to learn it.

In this tutorial you will make a tiny Express web app, write a Dockerfile for it, build and run it, and then reorder two lines so that changing your code no longer reinstalls every dependency. You will also run the app as an unprivileged user, which is a one-line change that matters. It is the second tutorial in the series From Docker to Kubernetes, and assumes Docker is installed as in /tutorials/install-docker-engine-on-ubuntu-26-04.

Step 1 · Create the app

Make a project folder with a package.json and the Express web framework:

Bash
mkdir hello-node
cd hello-node
npm init -y
npm install express

npm install may also print notices about funding or audit results, which you can ignore here. npm init -y writes a package.json with default answers. npm install express downloads Express into node_modules/ and records it in package.json and in package-lock.json. The lock file lists the exact version of every package, and the Dockerfile will use it for repeatable installs.

Write the app. It answers GET / with a line of JSON and listens on the port named in the PORT environment variable, or 3000 if there is none. The last lines handle SIGTERM, the signal docker stop sends. Inside a container, Node.js is the first process (PID 1), and Linux gives PID 1 no default reaction to SIGTERM. Without the handler, docker stop would wait ten seconds and then kill the app. If you cannot change the code, docker run --init adds a tiny init process that forwards signals for you:

Bash
cat > server.js <<'JS'
const express = require('express')

const app = express()
const port = process.env.PORT || 3000

app.get('/', (req, res) => {
  res.json({ message: 'Hello from a container', node: process.version })
})

const server = app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})

// Stop cleanly when Docker asks the container to stop.
process.on('SIGTERM', () => {
  server.close(() => process.exit(0))
})
JS

Check it worked

Run it directly, request it once, and stop it:

Bash
node server.js &
APP_PID=$!
sleep 2
curl -s http://localhost:3000/
kill $APP_PID

The reply is JSON with "message":"Hello from a container" and the Node.js version on your computer. The container will print a different version, the one inside the image, which is the point.

Step 2 · Write a first Dockerfile

Create a file named Dockerfile, with no extension, in the project folder:

Bash
cat > Dockerfile <<'DOCKER'
FROM node:26-slim

WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci --omit=dev

COPY server.js ./

ENV NODE_ENV=production
EXPOSE 3000

USER node
CMD ["node", "server.js"]
DOCKER

Each line is an instruction:

  • FROM node:26-slim picks the base image. It is Debian with Node.js 26 and little else. slim is much smaller than the default node:26 image, and it is easier to use than Alpine, which uses a different C library that some packages do not support.
  • WORKDIR /app sets the folder for every instruction after it, and creates it.
  • COPY package.json package-lock.json ./ copies only the two package files into the image.
  • RUN npm ci --omit=dev installs the exact versions in the lock file, and leaves out development dependencies. npm ci fails if the lock file and package.json disagree, which is what you want in a build.
  • COPY server.js ./ copies the app code after the dependencies are installed. The reason for this order is the next step's subject.
  • ENV NODE_ENV=production makes Express and many libraries switch to faster, quieter behaviour.
  • EXPOSE 3000 documents the port the app listens on. It does not publish it. Publishing is done when you run the container.
  • USER node makes everything after it, including the running app, run as the node user that the base image ships with, not as root. If an attacker finds a flaw in the app, they get a user with no special rights inside the container.
  • CMD ["node", "server.js"] is the command that starts the container. Write it in the list form shown, called exec form, so node itself is the main process and receives the stop signal. The string form would start a shell first, and the shell would not pass the signal on.

Keep your local files out of the image with a .dockerignore file. Without it, COPY could pull in node_modules from your computer, and any .env file next to the code:

Bash
cat > .dockerignore <<'IGNORE'
node_modules
npm-debug.log
.git
.env
.env.*
Dockerfile
.dockerignore
IGNORE

Step 3 · Build the image

Build it and give it a name and a tag. The dot at the end tells Docker to use the current folder as the build context:

Bash
docker build -t hello-node:1 .

Docker runs the instructions in order and prints each one. Depending on your Docker version, the progress shows as numbered steps (Step 4/9) or as BuildKit's #5 lines, and the older builder may print a deprecation notice. Both build the same image. The first build downloads the base image and installs the packages, so it takes a short while. Look at the result:

Bash
docker images hello-node

The list has one row, hello-node with the tag 1, and its size, a few hundred megabytes, mostly the Node.js runtime.

Troubleshooting

  • failed to read dockerfile: open Dockerfile: no such file or directory: you are in the wrong folder, or the file name is wrong. It is Dockerfile with a capital D.
  • npm error The npm ci command can only install with an existing package-lock.json: the lock file did not get copied. Check that package-lock.json exists next to the Dockerfile, and that .dockerignore does not list it.
  • permission denied while trying to connect to the Docker daemon socket: your user is not allowed to use Docker. On Linux, add yourself to the docker group as described in the Docker install tutorial, or put sudo in front.
  • COPY failed: file not found in build context: the file named in COPY is missing or excluded by .dockerignore.

Step 4 · Run the container

Run the image in the background (-d), publish port 3000 of the container as port 3000 of your machine (-p 127.0.0.1:3000:3000), and name it hello. The 127.0.0.1 part makes the port reachable from your own machine only. Without it, Docker publishes the port on every network interface:

Bash
docker run -d --name hello -p 127.0.0.1:3000:3000 hello-node:1

Docker prints the new container's ID. Make sure it is up:

Bash
docker ps --filter name=hello

Check it worked

Bash
curl -s http://localhost:3000/
docker logs hello

The reply is JSON again, now with the Node.js version from inside the image, a v26. number. docker logs prints Listening on port 3000. Confirm that the app is not running as root:

Bash
docker exec hello id

The output is uid=1000(node) gid=1000(node) groups=1000(node).

Change the port with an environment variable, without rebuilding. Publish another host port and pass PORT to the app. -e is fine for a plain setting like this one:

Bash
docker run -d --name hello-4000 -e PORT=4000 -p 127.0.0.1:4000:4000 hello-node:1
Bash
curl -s http://localhost:4000/
docker rm -f hello-4000

The app listens on 4000 inside the container, and the -p option publishes it. Do not put secrets in an ENV line in the Dockerfile: it is stored in the image for anyone to read with docker history. Do not pass them with -e either, because docker inspect shows every -e value to anyone who can run Docker commands, and the value lands in your shell history. For secrets, put them in a file that only you can read and pass it with docker run --env-file ./app.env, which keeps the values out of the command line. Create the file private first, then write the secret into it, so it is never readable by others. The value below is an example to replace:

Bash
install -m 600 /dev/null app.env
echo 'API_TOKEN=replace-with-the-real-token' >> app.env
ls -l app.env

The listing shows mode -rw-------. Pass it with --env-file ./app.env when you run a container that needs it. Keep app.env out of Git (see /tutorials/keep-secrets-out-of-git); the .dockerignore above already lists .env.* but not this name, so add app.env to it too. See /tutorials/keep-secrets-out-of-git for the habit.

Step 5 · Reorder for fast rebuilds

Docker saves the result of every instruction as a layer, and on the next build it reuses a layer if the instruction and everything it copies are unchanged. A changed layer invalidates every layer after it.

That is why the Dockerfile copies package.json and runs npm ci before it copies server.js. Your code changes many times a day, and your dependencies change rarely. With this order, a code change only rebuilds from the COPY server.js line on. Try it. Change the message and rebuild with a new tag:

Bash
sed -i.bak 's/Hello from a container/Hello again from a container/' server.js
rm server.js.bak
docker build -t hello-node:2 .

In the build output, the npm ci step is marked as using the cache (CACHED with BuildKit, or Using cache with the older builder), and only the COPY server.js step and the ones after it run. The rebuild takes a second or two instead of the time of a full install.

If the Dockerfile had been COPY . . followed by RUN npm ci, every code edit would copy a new file set in first, invalidate the layer, and reinstall every package. When your builds feel slow, check the order of the COPY and RUN lines first.

Replace the running container with the new image:

Bash
docker rm -f hello
docker run -d --name hello -p 127.0.0.1:3000:3000 hello-node:2
Bash
curl -s http://localhost:3000/

The reply now says Hello again from a container.

Step 6 · Stop and clean up

Containers and images take disk space until you remove them. Stop and remove the container, then the images:

Bash
docker stop hello
docker rm hello
docker rmi hello-node:1 hello-node:2

Each command prints the name or tag it removed. To see what else is on the machine, docker ps -a lists every container and docker images lists every image. docker system prune removes stopped containers and unused networks. It asks for confirmation first, and it never touches containers that are running.

Next steps

  • Run the app together with a database: /tutorials/docker-compose-app-with-postgres.
  • Make the image smaller with a second build stage: /tutorials/make-docker-images-smaller-multi-stage.
  • Run the container on Kubernetes: /tutorials/run-your-first-kubernetes-cluster-with-kind.
  • The instruction reference is at docs.docker.com/reference/dockerfile/.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.