How to Reduce Docker Image Size for a ReactJS Application from 1.43 GB to 22.4 MB
This tutorial shows step‑by‑step how to containerize a ReactJS app and dramatically shrink its Docker image using Alpine base images, multi‑stage builds, and Nginx, reducing the size from 1.43 GB to just 22.4 MB while preserving functionality.
Docker image size significantly impacts CI/CD and cloud deployment, so reducing it is valuable. This guide demonstrates how to containerize a simple ReactJS app and shrink its image from 1.43 GB to as low as 22.4 MB using several techniques.
Step 1: Create the project – Use the Create React App scaffold:
npx create-react-app docker-image-testThen install dependencies and start the app:
cd docker-image-test
yarn install
yarn startStep 2: Build the first image – Add a Dockerfile:
FROM node:12
WORKDIR /app
COPY package.json ./
RUN yarn install
COPY . .
EXPOSE 3000
CMD ["yarn","start"]Build and list the image:
docker build -t docker-image-test .
docker imagesThe resulting image is about 1.43 GB.
Step 3: Use a smaller base image – Replace node:12 with node:12-alpine , which reduces the size dramatically.
FROM node:12-alpine
WORKDIR /app
COPY package.json ./
RUN yarn install
COPY . .
EXPOSE 3000
CMD ["yarn","start"]After rebuilding, the image shrinks to roughly 580 MB.
Step 4: Multi‑stage build – Separate the build and runtime stages so that only the compiled assets are included in the final image.
# STAGE 1
FROM node:12-alpine AS build
WORKDIR /app
COPY package.json ./
RUN yarn install
COPY . /app
RUN yarn build
# STAGE 2
FROM node:12-alpine
WORKDIR /app
RUN npm install -g webserver.local
COPY --from=build /app/build ./build
EXPOSE 3000
CMD webserver.local -d ./buildThis reduces the image to about 97.5 MB.
Step 5: Serve with Nginx – Use an Nginx static server for the built assets, further cutting the image size.
# STAGE 1
FROM node:12-alpine AS build
WORKDIR /app
COPY package.json ./
RUN yarn install
COPY . /app
RUN yarn build
# STAGE 2
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx","-g","daemon off;"]The final image is only 22.4 MB and runs the React app efficiently.
These techniques—using Alpine base images, multi‑stage builds, and a lightweight web server—can be applied to any Node.js project to achieve much smaller, more portable Docker containers.
Cloud Native Technology Community
The Cloud Native Technology Community, part of the CNBPA Cloud Native Technology Practice Alliance, focuses on evangelizing cutting‑edge cloud‑native technologies and practical implementations. It shares in‑depth content, case studies, and event/meetup information on containers, Kubernetes, DevOps, Service Mesh, and other cloud‑native tech, along with updates from the CNBPA alliance.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.