Optimizing Docker Images: Reducing Size from 1.16 GB to 22.4 MB with Lightweight Base Images, Multi‑Stage Builds, and Nginx
This article explains how to dramatically shrink a Docker image for a React application—from over a gigabyte down to just 22 MB—by switching to Alpine base images, employing multi‑stage builds, and finally serving the compiled output with Nginx.
Docker is a platform that allows developers and system administrators to build, run, and share applications in containers, which encapsulate all dependencies in an image defined by a Dockerfile.
Containers are popular because they offer flexibility, lightweight operation, portability, loose coupling, and built‑in security.
The article focuses on optimizing Docker images for a React application to make them as small as possible.
Optimization Process
Starting from a basic Dockerfile, the generated image is 1.16 GB.
FROM node:10
WORKDIR /app
COPY app /app
RUN npm install -g webserver.local
RUN npm install && npm run build
EXPOSE 3000
CMD webserver.local -d ./buildStep 1: Use a lightweight base image (Alpine) – replacing the default Node image with node:10-alpine reduces the image to about 330 MB.
FROM node:10-alpine
WORKDIR /app
COPY app /app
RUN npm install -g webserver.local
RUN npm install && npm run build
EXPOSE 3000
CMD webserver.local -d ./buildStep 2: Apply multi‑stage builds – compile the app in one stage and copy only the built assets to a second stage, shrinking the image further to roughly 91.5 MB.
FROM node:10-alpine AS build
WORKDIR /app
COPY app /app
RUN npm install && npm run build
FROM node:10-alpine
WORKDIR /app
COPY --from=build /app/build ./build
EXPOSE 3000
CMD webserver.local -d ./buildStep 3: Serve static files with Nginx – replacing the Node runtime with nginx:stable-alpine yields a final image of about 22.4 MB.
FROM node:10-alpine AS build
WORKDIR /app
COPY app /app
RUN npm install && npm run build
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]After these three optimizations, the container runs the React application efficiently with a minimal footprint, as demonstrated by the accompanying screenshots showing image size reductions.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.