By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
Sign In
TechTonicTechTonicTechTonic
Notification Show More
Font ResizerAa
  • Home Technology
    • Home 2Hot
    • Home 3
    • Home 4
    • Home 5New
  • Technology
    Technology
    Modern technology has become a total phenomenon for civilization, the defining force of a new social order in which efficiency is no longer an option…
    Show More
    Top News
    Apple Jul Announcement: What a Refresh for Macbook
    Sponsored by
    Sponsored by
    Advantages and Disadvantages of Having Smartphone
    December 8, 2021
    Top 10 Best Portable Bluetooth Speakers for Summer Fun
    December 9, 2021
    Latest News
    The Invisible Architect: Why Human Thought Drives True Automation
    October 30, 2025
    The Groundhog Day of AI: When Your Automated Content Just Can’t Get It Together
    October 22, 2025
    Unmasking AI’s Blind Spot: Why “Later” Matters for Language Model Authority
    October 20, 2025
    Beyond the Brain Drain: Why Smart People Reuse Passwords and What Actually Works
    October 15, 2025
  • Gadget
    GadgetShow More
    The History and Future of CAD in Engineering
    From Drafting Boards to Digital Minds: The Transformative Journey of CAD and Its AI-Powered Horizon
    5 Min Read
    The Seven-Step Hostage Situation You Call Onboarding
    Investigating the Onboarding Blunder: When Helping Becomes a Hostage Situation
    12 Min Read
    Why Over-Caching Can Be Just as Bad as No Caching
    Beyond Optimization: Unmasking the Dangers of Excessive Caching
    9 Min Read
    Why SaaS Pricing Pages Fail
    Decoding Disappointment: An Investigation into SaaS Pricing Page Ineffectiveness
    10 Min Read
    Turning the Compiler Into Your Co-Architect
    Architecting Software with the Compiler: Enforcing Contracts Through Type Systems
    16 Min Read
  • Posts
    • Post Layouts
      • Standard 1
      • Standard 2
      • Standard 3
      • Standard 4
      • Standard 5
      • Standard 6
      • Standard 7
      • Standard 8
      • No Featured
    • Gallery Layouts
      • Layout 1
      • Layout 2
      • Layout 3
    • Video Layouts
      • Layout 1
      • Layout 2
    • Audio Layouts
      • Layout 1
      • Layout 2
      • Layout 3
    • Post Sidebar
      • Right Sidebar
      • Left Sidear
    • Content Features
      • Inline Mailchimp
      • Highlight Shares
      • Print Post
      • Inline Related
    • Auto Load Next Posts
    • Sponsored Post
  • Pages
    • Search Page
    • 404 Page
Reading: Shrink Your React Docker Image by 90% with Multi-Stage Builds
Share
TechTonicTechTonic
Font ResizerAa
  • Tech News
  • Gadget
  • Technology
  • Mobile
Search
  • Home
    • Home 1
    • Home 2
    • Home 3
    • Home 4
    • Home 5
  • Categories
    • Tech News
    • Gadget
    • Technology
    • Mobile
  • Bookmarks
  • More Foxiz
    • Sitemap
Have an existing account? Sign In
Follow US
  • Contact
  • Blog
  • Complaint
  • Advertise
© 2022 Foxiz News Network. Ruby Design Company. All Rights Reserved.
Uncategorized

Shrink Your React Docker Image by 90% with Multi-Stage Builds

AgentKyles
Last updated: October 11, 2025 10:10 am
AgentKyles
Share
SHARE

An essential tenet of modern DevOps is creating small, efficient Docker images. For a React/Vue application, a typical non-optimized image can balloon to hundreds of megabytes.

Contents
The Power of Multi-Stage Builds: From Bloat to MinimalOptimized Multi-Stage DockerfileStep-by-Step Optimization GuideHighlighting the Current Software Version (DevOps Insight)Final Optimized Dockerfile or Fast Deployment Is a Small Deployment.Conclusion: Ship Smart, Not HeavyLet’s Keep the Conversation Flowing

The best dependency is no dependency.

Press enter or click to view image in full size

By implementing Multi-Stage Builds and other key techniques, you can often achieve a 10x reduction in size, significantly improving deployment speed, reducing registry storage, and shrinking your attack surface.

This guide provides a step-by-step approach to dramatically reduce your React / Vue application’s Docker image size, including how to embed your software version for runtime identification.

The Power of Multi-Stage Builds: From Bloat to Minimal

A single-stage Dockerfile for a React app requires the entire Node.js environment, dependencies, and build tools in the final image, even though they’re only needed for the build process.

The solution is the Multi-Stage Build pattern. It separates the heavy build environment from the minimal runtime environment.

By using a multi-stage approach, we only include the tiny Built Static Files and a minimal web server in the final image.

Optimized Multi-Stage Dockerfile

We will use two stages:

Builder Stage: Uses a larger node:lts-alpine image to install dependencies and run npm run build (you can use yarn also). This stage is discarded after the build.

Final Stage: Uses the ultra-minimal nginx:alpine image to serve the static files copied from the builder stage.

The nginx:alpine image is typically only ~20 MB — a massive reduction from a Node.js-based image!

Step-by-Step Optimization Guide

\
Step 1: Initialize the DockerfileCreate a file named Dockerfile in the root of your React project.

\
Step 2: The builder StageThis stage is responsible for all the heavy lifting — installing Node, fetching dependencies, and compiling the React application.

\

# Stage 1: The Builder Stage
FROM node:lts-alpine AS builder

# Set the working directory inside the container
WORKDIR /app

# Copy package.json and lock file first to leverage Docker's build cache
# Only run npm install if package files change
COPY package*.json ./
RUN npm install

# Copy all other source files
COPY . .

# Run the build command - typically outputs to 'build' folder for Create-React-App
RUN npm run build

\
Optimization Notes for this Stage:

Minimal Base Image: We use node:lts-alpine instead of a full node:lts image. Alpine is a very small, security-focused Linux distribution.

Build Cache Leverage: Copying package*.json and running npm install before copying the rest of the source files ensures that Docker only re-runs the long npm install step if your dependencies change, not every time you change a source file.

\
Step 3: The final (Production) StageThis stage uses a lean, production-ready web server to host the built assets.

\

# Stage 2: The Final Production Stage
FROM nginx:alpine

# Copy the build output from the 'builder' stage to the Nginx public directory
# The 'build' directory is where 'npm run build' typically puts the static assets.
COPY --from=builder /app/build /usr/share/nginx/html

# Expose the port Nginx runs on
EXPOSE 80

# Command to start Nginx, serving the content
CMD ["nginx", "-g", "daemon off;"]

\
Key Optimization:

FROM nginx:alpine: Using an ultra-minimal image (around 20 MB) as the final layer.

COPY — from=builder: This is the magic of multi-stage builds. We only copy the small, compiled static files (/app/build) from the preceding stage, discarding the entire Node.js, node_modules, and build tool environment.

Highlighting the Current Software Version (DevOps Insight)

In DevOps, knowing the exact software version running in production is critical for debugging, rollbacks, and tracking.

We’ll use a Build Argument (ARG) to inject the version (e.g., from your CI/CD pipeline, Git tag, or Merge Request (MR) ID) into the image at build time, and then surface it in your application code.

\
Step 3.1: Pass the Version via Docker ARGModify the builder stage to accept a BUILD_VERSION argument:

\

# ... (Previous code)
# Stage 1: The Builder Stage
FROM node:lts-alpine AS builder
# Define a build argument for the software version
ARG BUILD_VERSION=unknown 

WORKDIR /app

# ... (rest of Stage 1 code)

# Build the app, passing the version as a variable to React's build process
# REACT_APP_VERSION is a standard pattern for exposing ENV vars to a React build
RUN npm run build

\
When building, you will pass the version:

\

# Example using a CI variable for the Merge Request ID
MR_ID="mr-12345"
docker build --build-arg BUILD_VERSION=${MR_ID} -t my-react-app:${MR_ID} .

\
Step 3.2: Access the Version in React (App Build/MR Code)You need to configure your React build process (e.g., in your project’s .env file, webpack config, or a special script) to consume the Docker ARG value and embed it into the application’s environment variables.

For a standard Create-React-App setup, you usually pass environment variables to the npm run build command. Since we can’t directly use an ARG as an ENV in a single command, the common and cleanest pattern is to use a simple script or directly embed the variable during the RUN instruction.

The Crucial Dockerfile Code (Combined RUN for npm run build):

To ensure the build argument is passed as an environment variable visible to the React build script:

\

# Stage 1: The Builder Stage
FROM node:lts-alpine AS builder
# Define a build argument for the software version
ARG BUILD_VERSION=unknown 

# ... (other setup)

# **HIGHLIGHTED APP BUILD/MR CODE INJECTION**
# Pass the BUILD_VERSION ARG as a REACT_APP_VERSION ENV to the build process
RUN REACT_APP_VERSION=${BUILD_VERSION} npm run build 
# Your app code (e.g., package.json scripts) should ensure this variable is embedded.

\
The Corresponding React Application Code (e.g., in App.js or a Footer component):

The React app’s code uses the standard way of accessing build-time environment variables:

\

import React from 'react';

function Footer() {
  // **HIGHLIGHTED APP BUILD/MR CODE**
  const version = process.env.REACT_APP_VERSION || 'local-dev';

  return (
    
Running Software Version: **{version}** 🚀
); } export default Footer;

\
This ensures that the Merge Request ID, Git SHA, or any other critical version identifier is baked directly into the static assets, easily visible to developers or support teams.

Final Optimized Dockerfile or Fast Deployment Is a Small Deployment.

Here is the complete, size-optimized, multi-stage Dockerfile with version injection:

\

# --------------------------------------------------------------------------------
# STAGE 1: BUILDER
# Uses a lean Node image to install dependencies and compile the React app
# --------------------------------------------------------------------------------
FROM node:lts-alpine AS builder

# Define a build argument for the version (default to 'unknown' if not provided)
ARG BUILD_VERSION=unknown

WORKDIR /app

# Copy package files first to enable caching of npm install
COPY package*.json ./
RUN npm install

# Copy application source code
COPY . .

# Pass the BUILD_VERSION as an environment variable during the build
# This value will be baked into the static assets (e.g., accessible via process.env.REACT_APP_VERSION)
# **HIGHLIGHTED APP BUILD/MR CODE**
RUN REACT_APP_VERSION=${BUILD_VERSION} npm run build

# --------------------------------------------------------------------------------
# STAGE 2: FINAL PRODUCTION IMAGE
# Uses a minimal Nginx image to serve the compiled static files
# --------------------------------------------------------------------------------
FROM nginx:alpine

# Copy the built React application files from the 'builder' stage
# This step discards the entire Node.js environment, reducing size by >90%
COPY --from=builder /app/build /usr/share/nginx/html

# Expose the standard HTTP port
EXPOSE 80

# Start Nginx
CMD ["nginx", "-g", "daemon off;"]

\
By following this approach, you move from a massive, single-stage image (often 1 GB+) to a lean, final image powered by Nginx Alpine (typically 50 MB) — easily achieving our 10x size reduction goal.

Conclusion: Ship Smart, Not Heavy

We’ve covered a lot of ground, from minimal base images to the genius of multi-stage builds. The ultimate takeaway is this: in the world of containers, less is more, and every megabyte counts.

By adopting the principles discussed — choosing an Alpine pencil case over a Debian suitcase, doing your cleanup in one layer, and using a .dockerignore file as your image’s velvet rope — you’re not just saving disk space; you’re buying back precious deployment time. You’re giving your CI/CD pipeline a fresh pair of running shoes.

Remember the DevOps mantra: “You build it, you run it.” A lean image is a reliable image, and reliability is the cornerstone of great operations. The effort you put in today to optimize your Dockerfile is a payment against future technical debt.

This journey of continuous improvement is not a destination, but a never-ending process.

Let’s Keep the Conversation Flowing

This article is just the tip of the iceberg. The best optimization is the one that fits your specific stack.

Got a tough image you just slimmed down? I’d love to hear your “honey, I shrunk the Docker” success story.

Don’t let this discussion be “out of sight, out of mind.” Feel free to reach out via LinkedIn or X.Com

Happy Containerizing!

\

You Might Also Like

Hello world!

GitHub’s Copilot Adds Cloud Agent to Draft Pull Requests Autonomously

GitHub Rolls Out Open-Source MCP Server to Expand Copilot’s Reach

Seamless Deployment Insights: Tracking Laravel Code Releases in New Relic with Custom Artisan Commands

How to Protect Your Kids Online When They’re Playing Video Games

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Share
Previous Article Pepeto Leads 2025 Bull Run with Audited Contracts and Whale Interest Pepeto’s Blueprint for Bull Run Leadership: Audited Foundations, DeFi Utility, and Meme Power
Next Article Context Engineering for Coding Agents
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1kLike
69.1kFollow
134kPin
54.3kFollow
banner banner
Create an Amazing Newspaper
Discover thousands of options, easy to customize layouts, one-click to import demo and much more.
Learn More

Latest News

Clean Code: Functions and Error Handling in Go: From Chaos to Clarity [Part 1]
Unmasking the Code Clutter: An Investigative Look into Go Functions and Error Handling Best Practices
backend best-practices clean-code clean-go-functions golang pass-code-review programming software-engineering
How Online Stores Know What You’ll Buy Next: The Math Behind “Frequently Bought Together”
The Algorithmic Oracle: Unpacking How E-commerce Predicts Your Next Purchase Ever feel like your favorite online store has a crystal ball, anticipating your desires before you even click ‘add to cart’? That eerie precision in suggesting “frequently bought together” items isn’t magic, dear reader, but a masterful application of data science, specifically something called Association Rule Mining. And trust me, it’s far more fascinating than any fortune teller. The core idea, stripped of its intimidating jargon, is elegantly simple: find patterns, then exploit them. Think of it as the digital equivalent of a savvy corner shop owner who knows that if you buy milk, you probably also need bread. Only, instead of one shop owner observing a few dozen customers, we’re talking about algorithms analyzing billions of transactions from millions of shoppers. The “If This, Then That” Goldmine At its heart, Association Rule Mining is about discovering “if-then” relationships within vast datasets. Computers sift through mountains of past purchase data to automatically identify rules like: “If a customer buys product A and product B, there’s an X% chance they’ll also buy product C.” These aren’t just guesses; they’re statistically significant insights derived from actual consumer behavior. This isn’t merely about throwing random suggestions at you. These algorithms employ metrics like ‘support’ (how often item sets appear together) and ‘confidence’ (how likely ‘if A’ leads to ‘then B’) to ensure the suggestions are not just correlations, but strong, reliable patterns. It’s about more than just popularity; it’s about *relationship*. From Digital Aisles to Physical Shelves The immediate application we all encounter is, of course, online. Those “Customers who bought this also bought…” or “Frequently bought together” sections on Amazon, eBay, or your local grocery delivery app? That’s Association Rule Mining in action, subtly nudging you towards complementary items, boosting the average order value for businesses, and, let’s be honest, sometimes genuinely reminding us we needed those batteries for the new gadget. But its genius isn’t confined to the digital realm. The same principles are used to optimize the physical layout of stores. Ever wondered why milk is often at the back of the supermarket, necessitating a trek past alluring displays? Or why chips and soda are frequently placed near each other? That’s often the result of this very analysis. It helps retailers organize shelves smarter, strategically placing items to maximize impulse purchases and enhance the shopping flow. Beyond the Cart: A Glimpse into the Algorithmic Future The implications of such pattern recognition extend far beyond retail. Imagine it being applied to: Healthcare: Identifying symptom patterns that frequently lead to specific diagnoses. Cybersecurity: Spotting sequences of network activities that often precede a security breach. Content Recommendations: Suggesting your next binge-watch based on your viewing history and what other similar viewers enjoyed. The ability of computers to find these hidden connections automatically from huge amounts of data empowers businesses and even other sectors to make better, more data-driven decisions. The Double-Edged Sword of Predictive Power While undoubtedly convenient, enhancing our shopping experience and making businesses more efficient, it’s worth pausing to consider the deeper implications. As these algorithms become more sophisticated, predicting our behavior with unsettling accuracy, we must ask ourselves: are these suggestions truly serving *our* best interests, or are they subtly guiding us down a pre-determined path to consume more? Are we trading true serendipity and discovery for optimized efficiency, potentially boxing ourselves into algorithmic echo chambers of preference? In a world increasingly shaped by these unseen rules, how do we ensure we remain the choosers, not just the chosen?
association-rule-mining ecommerce ecommerce-marketplace ecommerce-store frequently-bought-together item-recommendations machine-learning recommendation-algorithm
Own Your Edge: Control your AI
Beyond the Brink: Unpacking the 95% Failure Rate in Retail Edge AI and How to Own Your Edge
AI ai-edge-computing ai-infrastructure computer-vision-ai edge-ai edge-computing own-your-edge retail-ai
The Road to Hell is Paved with Good DRY Intentions
DRY Intentions, Wet Outcomes: Navigating the Over-Engineered Minefield in Software Development
design-patterns dry engineering hackernoon-top-story modular-reasoning modularity software-development yagni

You Might also Like

Developers Embrace Taskmaster, an AI Scrum Master for Code

AgentKyles
AgentKyles
0 Min Read

Windsurf Expands Free Plan to Woo Developers Amid AI IDE Competition

AgentKyles
AgentKyles
0 Min Read

Context Engineering for Coding Agents

AgentKyles
AgentKyles
9 Min Read
//

We influence 20 million users and is the number one business and technology news network on the planet

Quick Link

  • Contact
  • Blog
  • Complaint
  • Advertise

Support

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

[mc4wp_form id=”1616″]

TechTonicTechTonic
Follow US
© 2022 Foxiz News Network. Ruby Design Company. All Rights Reserved.
Join Us!
Subscribe to our newsletter and never miss our latest news, podcasts etc..
[mc4wp_form]
Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?