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:
mkdir hello-node
cd hello-node
npm init -y
npm install expressnpm 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:
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))
})
JSCheck it worked
Run it directly, request it once, and stop it:
node server.js &
APP_PID=$!
sleep 2
curl -s http://localhost:3000/
kill $APP_PIDThe 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:
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"]
DOCKEREach line is an instruction:
FROM node:26-slimpicks the base image. It is Debian with Node.js 26 and little else.slimis much smaller than the defaultnode:26image, and it is easier to use than Alpine, which uses a different C library that some packages do not support.WORKDIR /appsets 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=devinstalls the exact versions in the lock file, and leaves out development dependencies.npm cifails if the lock file andpackage.jsondisagree, 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=productionmakes Express and many libraries switch to faster, quieter behaviour.EXPOSE 3000documents the port the app listens on. It does not publish it. Publishing is done when you run the container.USER nodemakes everything after it, including the running app, run as thenodeuser 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, sonodeitself 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:
cat > .dockerignore <<'IGNORE'
node_modules
npm-debug.log
.git
.env
.env.*
Dockerfile
.dockerignore
IGNOREStep 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:
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:
docker images hello-nodeThe 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 isDockerfilewith 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 thatpackage-lock.jsonexists next to the Dockerfile, and that.dockerignoredoes 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 thedockergroup as described in the Docker install tutorial, or putsudoin front.COPY failed: file not found in build context: the file named inCOPYis 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:
docker run -d --name hello -p 127.0.0.1:3000:3000 hello-node:1Docker prints the new container's ID. Make sure it is up:
docker ps --filter name=helloCheck it worked
curl -s http://localhost:3000/
docker logs helloThe 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:
docker exec hello idThe 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:
docker run -d --name hello-4000 -e PORT=4000 -p 127.0.0.1:4000:4000 hello-node:1curl -s http://localhost:4000/
docker rm -f hello-4000The 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:
install -m 600 /dev/null app.env
echo 'API_TOKEN=replace-with-the-real-token' >> app.env
ls -l app.envThe 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:
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:
docker rm -f hello
docker run -d --name hello -p 127.0.0.1:3000:3000 hello-node:2curl -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:
docker stop hello
docker rm hello
docker rmi hello-node:1 hello-node:2Each 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/.
Related tutorials
- How to Run Your First Kubernetes Cluster Locally with kindYou will create a one-node Kubernetes 1.37 cluster inside Docker with kind, talk to it with kubectl, run a pod from a public image and from an image built on your own machine, and delete the cluster when you are done.
- How to Shrink Docker Images with Multi-Stage BuildsYou will build the same small web site into two Docker images, one in a single stage and one in two, and see the second come out several times smaller because it ships only the built files and a web server.
- How to Configure a Kubernetes App with ConfigMaps and SecretsYou will keep settings and credentials out of your container image by passing them to a Kubernetes 1.37 Deployment as environment variables and as mounted files, update them without rebuilding, and learn what a Secret does and does not protect.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials