Skip to main content

Containers and Kubernetes · Intermediate · 13 min

How to Shrink Docker Images with Multi-Stage Builds

By Padding · Updated 15 Nov 2026
Docker Engine 29

You 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.

On this page

Many apps need tools to build that they do not need to run. A web site needs Node.js and a bundler to turn source files into a few static files, but once those files exist, serving them takes only a web server. If your Dockerfile installs the build tools and keeps them, every server that pulls the image downloads them and every security scanner has to read them.

A multi-stage build fixes this inside one Dockerfile. It has several FROM lines. Each starts a new stage, and the last stage becomes the image. Earlier stages exist to produce files, which you copy forward with COPY --from. Everything else in them is thrown away. In this tutorial you will build one small site both ways and compare the results.

Step 1 · Create a site with a build step

Make a project folder. The site is one HTML page and one JavaScript file, which the bundler esbuild compiles into a dist folder. esbuild is a development dependency: it is needed to build and never to run.

Bash
mkdir site
cd site
npm init -y
npm install --save-dev esbuild
mkdir src

Write the page and the script:

Bash
cat > src/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Multi-stage demo</title>
</head>
<body>
  <h1>Multi-stage demo</h1>
  <p id="out"></p>
  <script src="/main.js"></script>
</body>
</html>
HTML

cat > src/main.js <<'JS'
const built = new Date().getFullYear()
document.getElementById('out').textContent = `Bundled with esbuild, shown in ${built}.`
JS

Add a build script to package.json. It bundles and minifies the script into dist and copies the page next to it:

Bash
npm pkg set scripts.build="esbuild src/main.js --bundle --minify --outfile=dist/main.js && cp src/index.html dist/index.html"
npm run build
ls dist

ls dist shows index.html and main.js. Those two small files are the whole product. Everything else in the folder, including node_modules, is only there to make them.

Keep local files out of any image with a .dockerignore:

Bash
cat > .dockerignore <<'IGNORE'
node_modules
dist
.git
.env
.env.*
IGNORE

Step 2 · Build a single-stage baseline

First do it the straightforward way: one stage that installs everything, builds the site, and serves it with a few lines of Node.js. Write the tiny server:

Bash
cat > server.js <<'JS'
const http = require('node:http')
const fs = require('node:fs')
const path = require('node:path')

const types = { '.html': 'text/html', '.js': 'text/javascript' }

http
  .createServer((req, res) => {
    const name = req.url === '/' ? 'index.html' : path.basename(req.url)
    fs.readFile(path.join(__dirname, 'dist', name), (err, data) => {
      if (err) {
        res.writeHead(404).end('Not found')
        return
      }
      res.writeHead(200, { 'Content-Type': types[path.extname(name)] || 'text/plain' }).end(data)
    })
  })
  .listen(8080)
JS

Then the Dockerfile. It keeps the build tools in the final image, because there is only one stage. Name it Dockerfile.single so that you can keep two Dockerfiles in the folder:

Bash
cat > Dockerfile.single <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY src ./src
COPY server.js ./
RUN npm run build
EXPOSE 8080
USER node
CMD ["node", "server.js"]
DOCKER

docker build -f Dockerfile.single -t site:single .

-f picks a Dockerfile other than the default name. This image contains the Node.js runtime, node_modules with esbuild in it, the source files and the output. Only the output is needed to serve the site.

Step 3 · Rewrite it as a multi-stage build

Now the same build in two stages. The first stage, named build with AS, installs the tools and produces dist. The second starts again from a fresh, small web server image and copies in only that folder:

Bash
cat > Dockerfile <<'DOCKER'
FROM node:26-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY src ./src
RUN npm run build

FROM nginx:1.30-alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
DOCKER

docker build -t site:multi .

Read it from the bottom up:

  • FROM nginx:1.30-alpine begins the final stage. Nothing from the build stage exists here unless you copy it. Nginx 1.30 on Alpine Linux is a complete web server image in under 100 MB (92 MB was measured for the image built here).
  • COPY --from=build /app/dist /usr/share/nginx/html copies one folder out of the build stage into the folder from which Nginx serves files. --from also accepts a stage number (--from=0) or another image name, such as --from=alpine.
  • The build stage is the same as the single-stage Dockerfile, without the server. It is not part of the final image. Its layers stay in your local build cache, which is why a rebuild is fast, but they are not shipped when you push or pull site:multi.

The Dockerfile has no USER line. The official Nginx image starts its main process as root so that it can listen on port 80, and then runs the workers as the nginx user. If you must run without root at all, the Nginx project publishes a variant, nginxinc/nginx-unprivileged, which listens on port 8080 instead.

Step 4 · Compare the sizes

Bash
docker image ls site --format 'table {{.Repository}}:{{.Tag}}\t{{.Size}}'

The table has two rows. The single-stage image is about 400 MB, mostly the Node.js runtime and node_modules. The multi-stage one is about 90 MB (the sizes when this was written, on an Arm machine), because it is Alpine Linux, Nginx and two files. The numbers differ by platform and by the day's base images; a gap of several times does not. A smaller image pulls faster on every deploy, uses less registry space, and has fewer packages for a vulnerability scanner to flag.

Check it worked

Run the small image and request the page. The 127.0.0.1 in -p keeps the port reachable from your own machine only:

Bash
docker run -d --name site-multi -p 127.0.0.1:8080:80 site:multi
Bash
curl -s http://localhost:8080/ | head -n 5
curl -s http://localhost:8080/main.js

The first request returns the start of the HTML page and the second the minified script. Confirm that the build tools are gone from the final image. This command looks for node and esbuild inside it:

Bash
docker exec site-multi sh -c 'command -v node || echo "no node"; ls /app 2>/dev/null || echo "no /app"'

It prints no node and no /app.

Troubleshooting

  • COPY failed: stat app/dist: file does not exist or failed to compute cache key ... "/app/dist": not found: the build stage did not produce dist, or the path differs. WORKDIR /app plus npm run build writes to /app/dist; check the --outfile path in the build script.
  • invalid from flag value build: pull access denied: the stage name in --from= does not match the AS name, or the name has different capitalisation.
  • The page loads but the script does not: the HTML asks for /main.js. Check that dist/main.js exists in the final image with docker exec site-multi ls /usr/share/nginx/html.

Step 5 · Stop at one stage while debugging

When a build fails halfway, you can build only up to a named stage and look inside it. --target stops after the stage you name:

Bash
docker build --target build -t site:build .
docker run --rm site:build ls /app/dist

The listing is index.html and main.js. This is also how you build a development image from the same Dockerfile as the production one: add a stage with extra tools, and select it with --target only on your own machine.

Step 6 · Clean up

Stop the container and remove the three images:

Bash
docker stop site-multi
docker rm site-multi
docker rmi site:single site:multi site:build

The base images node:26-slim and nginx:1.30-alpine stay in your local cache so that the next build is fast. docker image ls lists them and docker rmi removes them if you need the space.

Next steps

  • Run this image together with a database: /tutorials/docker-compose-app-with-postgres.
  • Run it on Kubernetes: /tutorials/run-your-first-kubernetes-cluster-with-kind.
  • Read the reference for multi-stage builds at docs.docker.com/build/building/multi-stage/.

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.