For a React/Vue application, a typical non-optimized image can balloon to hundreds of megabytes.For a React/Vue application, a typical non-optimized image can balloon to hundreds of megabytes.

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

2025/10/11 12:00

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.

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 (     <footer>       Running Software Version: **{version}** 🚀     </footer>   ); }  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!

\

ข้อจำกัดความรับผิดชอบ: บทความที่โพสต์ซ้ำในไซต์นี้มาจากแพลตฟอร์มสาธารณะและมีไว้เพื่อจุดประสงค์ในการให้ข้อมูลเท่านั้น ซึ่งไม่ได้สะท้อนถึงมุมมองของ MEXC แต่อย่างใด ลิขสิทธิ์ทั้งหมดยังคงเป็นของผู้เขียนดั้งเดิม หากคุณเชื่อว่าเนื้อหาใดละเมิดสิทธิของบุคคลที่สาม โปรดติดต่อ service@mexc.com เพื่อลบออก MEXC ไม่รับประกันความถูกต้อง ความสมบูรณ์ หรือความทันเวลาของเนื้อหาใดๆ และไม่รับผิดชอบต่อการดำเนินการใดๆ ที่เกิดขึ้นตามข้อมูลที่ให้มา เนื้อหานี้ไม่ถือเป็นคำแนะนำทางการเงิน กฎหมาย หรือคำแนะนำจากผู้เชี่ยวชาญอื่นๆ และไม่ถือว่าเป็นคำแนะนำหรือการรับรองจาก MEXC
แชร์ข้อมูลเชิงลึก

คุณอาจชอบเช่นกัน

BlackRock boosts AI and US equity exposure in $185 billion models

BlackRock boosts AI and US equity exposure in $185 billion models

The post BlackRock boosts AI and US equity exposure in $185 billion models appeared on BitcoinEthereumNews.com. BlackRock is steering $185 billion worth of model portfolios deeper into US stocks and artificial intelligence. The decision came this week as the asset manager adjusted its entire model suite, increasing its equity allocation and dumping exposure to international developed markets. The firm now sits 2% overweight on stocks, after money moved between several of its biggest exchange-traded funds. This wasn’t a slow shuffle. Billions flowed across multiple ETFs on Tuesday as BlackRock executed the realignment. The iShares S&P 100 ETF (OEF) alone brought in $3.4 billion, the largest single-day haul in its history. The iShares Core S&P 500 ETF (IVV) collected $2.3 billion, while the iShares US Equity Factor Rotation Active ETF (DYNF) added nearly $2 billion. The rebalancing triggered swift inflows and outflows that realigned investor exposure on the back of performance data and macroeconomic outlooks. BlackRock raises equities on strong US earnings The model updates come as BlackRock backs the rally in American stocks, fueled by strong earnings and optimism around rate cuts. In an investment letter obtained by Bloomberg, the firm said US companies have delivered 11% earnings growth since the third quarter of 2024. Meanwhile, earnings across other developed markets barely touched 2%. That gap helped push the decision to drop international holdings in favor of American ones. Michael Gates, lead portfolio manager for BlackRock’s Target Allocation ETF model portfolio suite, said the US market is the only one showing consistency in sales growth, profit delivery, and revisions in analyst forecasts. “The US equity market continues to stand alone in terms of earnings delivery, sales growth and sustainable trends in analyst estimates and revisions,” Michael wrote. He added that non-US developed markets lagged far behind, especially when it came to sales. This week’s changes reflect that position. The move was made ahead of the Federal…
แชร์
BitcoinEthereumNews2025/09/18 01:44
แชร์
UK Looks to US to Adopt More Crypto-Friendly Approach

UK Looks to US to Adopt More Crypto-Friendly Approach

The post UK Looks to US to Adopt More Crypto-Friendly Approach appeared on BitcoinEthereumNews.com. The UK and US are reportedly preparing to deepen cooperation on digital assets, with Britain looking to copy the Trump administration’s crypto-friendly stance in a bid to boost innovation.  UK Chancellor Rachel Reeves and US Treasury Secretary Scott Bessent discussed on Tuesday how the two nations could strengthen their coordination on crypto, the Financial Times reported on Tuesday, citing people familiar with the matter.  The discussions also involved representatives from crypto companies, including Coinbase, Circle Internet Group and Ripple, with executives from the Bank of America, Barclays and Citi also attending, according to the report. The agreement was made “last-minute” after crypto advocacy groups urged the UK government on Thursday to adopt a more open stance toward the industry, claiming its cautious approach to the sector has left the country lagging in innovation and policy.  Source: Rachel Reeves Deal to include stablecoins, look to unlock adoption Any deal between the countries is likely to include stablecoins, the Financial Times reported, an area of crypto that US President Donald Trump made a policy priority and in which his family has significant business interests. The Financial Times reported on Monday that UK crypto advocacy groups also slammed the Bank of England’s proposal to limit individual stablecoin holdings to between 10,000 British pounds ($13,650) and 20,000 pounds ($27,300), claiming it would be difficult and expensive to implement. UK banks appear to have slowed adoption too, with around 40% of 2,000 recently surveyed crypto investors saying that their banks had either blocked or delayed a payment to a crypto provider.  Many of these actions have been linked to concerns over volatility, fraud and scams. The UK has made some progress on crypto regulation recently, proposing a framework in May that would see crypto exchanges, dealers, and agents treated similarly to traditional finance firms, with…
แชร์
BitcoinEthereumNews2025/09/18 02:21
แชร์