{"id":81214,"date":"2026-08-12T23:24:12","date_gmt":"2026-08-12T17:54:12","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=81214"},"modified":"2026-08-21T14:42:02","modified_gmt":"2026-08-21T09:12:02","slug":"shrink-your-node-js-docker-image-with-multi-stage-builds","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/shrink-your-node-js-docker-image-with-multi-stage-builds\/","title":{"rendered":"Shrink Your Node.js Docker Image With Multi-Stage Builds"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>The first time I shipped a Node.js service to production, I ran <code>docker images<\/code> out of habit and stared at the number for a good ten seconds. The image was 1.1 GB, for an app whose actual code was only a few hundred kilobytes.<\/p>\n<p>It still worked, so I let it slide. Then the deploys started getting slower, our registry storage bill crept up, and a security scan flagged a pile of build tools that had no business being in a running container. That 1.1 GB was the problem. A multi-stage Docker build is how we got it down to about 150 MB without changing a single line of application code.<\/p>\n<h2>Why Your Node.js Image Gets So Big<\/h2>\n<p>When you build a Node app inside Docker, you need a lot of stuff <em>at build time<\/em>:<\/p>\n<ul>\n<li>The full <code>node_modules<\/code> folder, including dev dependencies like TypeScript, webpack, Babel, and testing libraries<\/li>\n<li>Your raw source code<\/li>\n<li>Compilers and build tooling<\/li>\n<\/ul>\n<p>But when the app is actually <em>running<\/em>, it needs almost none of that. It needs the compiled output and the production dependencies. That is it.<\/p>\n<p>With a plain, single-stage Dockerfile, everything you pulled in to build the app stays inside the final image. All that tooling rides along to production as dead weight: bigger images, slower deploys, and a larger surface for something to go wrong.<\/p>\n<h2>What Is a Multi-Stage Docker Build?<\/h2>\n<p>A multi-stage build lets you use more than one <code>FROM<\/code> statement in a single Dockerfile. Each <code>FROM<\/code> starts a fresh stage with its own base image. Do the heavy lifting in one stage, then copy just the finished output into a clean final stage and throw the rest away.<\/p>\n<p>Think of it like a kitchen. Cooking needs pans, a board, and gas, and it leaves a pile of scraps. But you serve the customer the plate, not the whole kitchen. The build stage is the messy kitchen; the final stage is the plate.<\/p>\n<p>&nbsp;<\/p>\n<h2>The Single-Stage Dockerfile We Started With<\/h2>\n<p>This is roughly what our original file looked like:<\/p>\n<pre>FROM node:20\r\nWORKDIR \/app\r\nCOPY package*.json .\/\r\nRUN npm install\r\nCOPY . .\r\nRUN npm run build\r\nCMD [\"node\", \"dist\/index.js\"]<\/pre>\n<p>It works, but the full <code>node:20<\/code> base image, every dev dependency, and all the source code get baked into the image you ship. Nothing is thrown away.<\/p>\n<h2>Rewriting It as a Multi-Stage Build<\/h2>\n<p>Here is the same app, restructured into two stages:<\/p>\n<pre># ---- Stage 1: build ----\r\nFROM node:20 AS builder\r\nWORKDIR \/app\r\nCOPY package*.json .\/\r\nRUN npm install\r\nCOPY . .\r\nRUN npm run build\r\n\r\n# ---- Stage 2: runtime ----\r\nFROM node:20-alpine\r\nWORKDIR \/app\r\nENV NODE_ENV=production\r\nCOPY package*.json .\/\r\nRUN npm install --omit=dev\r\nCOPY --from=builder \/app\/dist .\/dist\r\nCMD [\"node\", \"dist\/index.js\"]<\/pre>\n<p>Two things changed. The first stage is named <code>builder<\/code> and does all the installing and compiling. The second stage starts from <code>node:20-alpine<\/code>, a much smaller base. It installs only production dependencies and pulls in the compiled <code>dist<\/code> folder from the first stage.<\/p>\n<h3>What That <code>COPY --from<\/code> Line Actually Does<\/h3>\n<p><code>COPY --from=builder \/app\/dist .\/dist<\/code> is the one line doing the real work here. It reaches back into the <code>builder<\/code> stage and copies out just the compiled output. Everything else from that stage (the dev dependencies, the source, the build tools) never makes it into the final image.<\/p>\n<p>Docker only ships the last stage; earlier stages are just a source to copy from, then discarded. All that build-time weight never travels to production.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter\" style=\"max-width: 100%; height: auto;\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2026\/08\/docker-stages.png\" alt=\"multi-stage Docker build flow from build stage to shipped image\" width=\"720\" \/><\/p>\n<h2>The Results: An 85% Smaller Docker Image<\/h2>\n<p>Same app, same behaviour, very different image. Running <code>docker images<\/code> after each build tells the whole story (trimmed to the columns that matter):<\/p>\n<pre>REPOSITORY  TAG           SIZE\r\nmy-api       single-stage   1.1GB\r\nmy-api       multi-stage    150MB<\/pre>\n<p><img decoding=\"async\" class=\"aligncenter\" style=\"max-width: 100%; height: auto;\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2026\/08\/docker-size.png\" alt=\"Docker image size comparison single-stage 1.1 GB vs multi-stage 150 MB\" width=\"450\" \/><\/p>\n<p>That is roughly an 85% cut. Your exact numbers depend on your app and base image, but the direction is always the same: smaller images push and pull faster, so deploys and autoscaling stop dragging. You also stop paying to store a gigabyte of build tools you never run, and your security scanner has less to complain about.<\/p>\n<h2>Do Not Forget a .dockerignore File<\/h2>\n<p>A multi-stage build only helps if you are not quietly copying junk into the build context in the first place. A <code>.dockerignore<\/code> file keeps local clutter out of every <code>COPY<\/code>:<\/p>\n<pre>node_modules\r\nnpm-debug.log\r\n.git\r\n.env\r\ndist\r\nDockerfile\r\n<\/pre>\n<p>Without this, a <code>COPY . .<\/code> can drag in your local <code>node_modules<\/code> or a stray <code>.env<\/code> file, which slows the build and, in the case of secrets, creates a real security problem. Treat it like <code>.gitignore<\/code> for your image.<\/p>\n<h2>Common Mistakes to Avoid<\/h2>\n<p>A few of these bit us (or people whose PRs I have reviewed) more than once:<\/p>\n<ul>\n<li><strong>Copying <code>node_modules<\/code> from the host.<\/strong> Let Docker install deps inside the image; host copies can pull in the wrong platform binaries and break at runtime.<\/li>\n<li><strong>Wrong layer order.<\/strong> A <code>COPY . .<\/code> before installing means every code change busts that layer&#8217;s build cache and forces a full reinstall. Copy <code>package*.json<\/code> and install first.<\/li>\n<li><strong>Leaving dev dependencies in the final stage.<\/strong> Use <code>npm install --omit=dev<\/code> (or <code>npm ci --omit=dev<\/code>, which needs a committed <code>package-lock.json<\/code>) in the runtime stage so testing and build-only packages never ship.<\/li>\n<li><strong>Forgetting to copy runtime assets.<\/strong> If your app needs more than the compiled code (templates, migrations, static files), remember to <code>COPY --from=builder<\/code> those too, or the container will start and then fall over.<\/li>\n<\/ul>\n<h2>When You Might Not Need This<\/h2>\n<p>Multi-stage builds are worth it for almost any real service, but they are not a law. A tiny script with no build step and a handful of dependencies is fine on a single well-trimmed stage. The moment you have a compile step, dev-only tooling, or an image you deploy often, though, the split pays for itself.<\/p>\n<h2>Conclusion<\/h2>\n<p>Multi-stage builds gave us a smaller, faster, safer image for the price of restructuring one file. No code changes, no new tools, no separate build scripts, just a clean separation between how the app is built and how it runs.<\/p>\n<p>Pull up one of your own images, run <code>docker images<\/code>, and see the number. Then split the Dockerfile into a build stage and a runtime stage and measure the difference. For most Node images, it is the easiest win on the table.<\/p>\n<p>Found this useful? Leave a comment with your before-and-after image sizes.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction The first time I shipped a Node.js service to production, I ran docker images out of habit and stared at the number for a good ten seconds. The image was 1.1 GB, for an app whose actual code was only a few hundred kilobytes. It still worked, so I let it slide. Then the [&hellip;]<\/p>\n","protected":false},"author":1714,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":1},"categories":[5876],"tags":[1891,1892,1883,2558,8808,1177],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/81214"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1714"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=81214"}],"version-history":[{"count":4,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/81214\/revisions"}],"predecessor-version":[{"id":81737,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/81214\/revisions\/81737"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=81214"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=81214"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=81214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}