Creating a Docker Container for React: Installing Dependencies Once

Abstract: Solves bloated Docker images by using multi-stage builds to install React dependencies once and exclude build tools from the final runtime.

Created: 2026-08-05 by
To install React dependencies only once in a Docker container, you must leverage multi-stage builds to separate the build environment from the runtime environment. This approach ensures that heavy compilation tools and node modules are not carried over into the final image, significantly reducing size and improving security while maintaining fast startup times for your application.

The Problem with Standard Builds

When developers first attempt to containerize a React application, they often create a single Dockerfile that installs all dependencies, builds the static assets, and then runs the development server or serves the files. While this works locally, it leads to bloated images because the final container contains the entire Node.js source tree, compiler artifacts, and development dependencies. Furthermore, every time code changes, Docker may re-run the expensive dependency installation step if caching is not managed perfectly. The goal is to isolate the build phase so that only the necessary production-ready files are copied into the final runtime stage.

Setting Up the Multi-Stage Build

A multi-stage build allows you to define multiple FROM instructions within a single Dockerfile. Each stage starts fresh, inheriting from a base image but discarding previous layers unless explicitly copied. The first stage will act as the builder, where we install all dependencies and compile the React app. The second stage will be the minimal runtime, containing only the web server needed to serve the compiled output. This separation is critical for achieving the "install once" efficiency you seek. Start by defining the builder stage using a standard Node.js image. You should specify a version that matches your local development environment to avoid compatibility issues. Inside this stage, set the working directory and copy the package files first. This strategy exploits Docker's layer caching; since package.json and package-lock.json change less frequently than source code, Docker can skip the installation step if these files remain unchanged.
FROM node:18-alpine AS builder

WORKDIR /app

COPY package*.json ./

RUN npm ci --only=production

COPY . .

RUN npm run build
The command npm ci is preferred over npm install in CI/CD and containerized environments because it performs a clean install based strictly on the lock file, ensuring deterministic builds. By specifying --only=production, you exclude dev dependencies like testing libraries or linters, which are not needed in the final container. After installing dependencies, the full source code is copied, and the build script generates the optimized static files in the build directory.

Creating the Minimal Runtime Image

The second stage focuses on serving the application efficiently. Instead of using a large Node.js image, you can use an even lighter HTTP server like Nginx or Apache, or a minimal Node.js image configured to serve static files. Using Nginx is a common choice for React apps because it handles static content delivery very efficiently.
FROM nginx:alpine

COPY --from=builder /app/build /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
In this snippet, the COPY --from=builder instruction copies the compiled output from the first stage directly into the Nginx document root. Notice that no npm install or source code is present in this stage. The resulting image contains only the Nginx binary, the configuration, and the static HTML/CSS/JS files. This drastically reduces the image size compared to keeping the Node.js runtime and source code.

Building and Running the Container

Once the Dockerfile is structured this way, building the image is straightforward. Use the standard docker build command. Docker will automatically execute the stages in order, creating intermediate containers for each stage but only retaining the final result.
docker build -t my-react-app .
After the build completes, you can run the container. The application will be accessible on port 80 (or mapped to a host port) without requiring any further installation steps. If you modify your React source code, Docker’s cache invalidation will trigger the build stage again, but the dependency installation will still be cached unless package.json changes, ensuring that the most time-consuming part of the process is skipped whenever possible.

Optimizing Cache Invalidation

To maximize the "install once" benefit, ensure that you do not copy unnecessary files before copying package.json. If you copy the entire project directory before installing dependencies, Docker cannot reuse the cache layer for npm ci even if the packages haven't changed. Always copy the manifest files first, run the install, and then copy the rest of the source code. This order guarantees that dependency installation is truly isolated and cached effectively.

Frequently Asked Questions

Why does my Docker image still have a large size?

If your image remains large, check if you are accidentally copying the node_modules folder from the host into the final stage. Ensure you are using COPY --from=builder to move only the built artifacts and not the source directory. Also, verify that you are using a slim or alpine variant for your base images to reduce overhead.

Can I use yarn instead of npm for faster installs?

Yes, you can replace npm ci with yarn install --frozen-lockfile if your project uses Yarn. The principle remains the same: copy the lock file first, install dependencies, and then copy the source code. Yarn often provides faster installation speeds due to its parallel processing capabilities, which can further reduce build times.

What happens if I update a dependency in package.json?

When package.json changes, Docker detects that the layer has been modified and will invalidate the cache for all subsequent steps. This means npm ci will run again to fetch the new dependencies. This is expected behavior and ensures your container always reflects the correct dependency tree defined in your manifest.

Is it safe to remove devDependencies in production?

Yes, removing devDependencies is a best practice for production containers. DevDependencies include tools like Jest, ESLint, and TypeScript compilers, which are only needed during development. Excluding them reduces the attack surface and storage footprint, making your container more secure and efficient.

How do I handle environment variables in the built app?

React applications typically inject environment variables at build time using REACT_APP_ prefixed variables. These values are baked into the static JavaScript files during the npm run build step. Therefore, you cannot change them at runtime without rebuilding the image. For dynamic configuration, consider using a separate config service or modifying the Nginx configuration to proxy requests.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More