This repository provides a step-by-step production and development guide on how to containerize a React application using Docker. Containerizing your React app ensures deterministic builds, isolates dependencies, and enables seamless deployment across any cloud provider or orchestration platform (AWS EC2, EKS, ECS, GCP Cloud Run, Docker Swarm).
flowchart LR
Dev["React App Source Code<br/>(JSX / CSS / JSON)"] --> Build["Docker Build<br/><code>node:alpine</code>"]
Build --> Image["Docker Container Image<br/>(react-app:latest)"]
Image --> Run["Docker Run<br/><code>-p 3000:3000</code>"]
Run --> Browser["Client Browser<br/><code>http://localhost:3000</code>"]
📺 Watch Full Video Walkthrough on YouTube: How to Dockerize a React Application
Before you begin, ensure you have the following installed on your system:
- Docker: Install Docker
-
Clone the Repository:
git clone https://github.com/codewithmuh/dockerize_react.git cd dockerize_react -
Create a Dockerfile:
Create a file named Dockerfile in the root of your project with the following content:
# Use Node.js Alpine base image
FROM node:alpine
# Create and set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package.json package-lock.json /app/
# Install dependencies
RUN npm install
# Copy the entire codebase to the working directory
COPY . /app/
# Expose the port your app runs on (replace <PORT_NUMBER> with your app's actual port)
EXPOSE 3000
# Define the command to start your application (replace "start" with the actual command to start your app)
CMD ["npm", "start"]- Build the Docker Image:
Build the Docker image using the following command:
docker build -t react-app .Replace your-react-app with a suitable image name. Run the Docker Container:
Run the Docker container using the following command:
docker run -p 3000:3000 -d react-app
This maps port 3000 on your local machine to port 3000 in the Docker container.
Access Your React Application:
Open your web browser and navigate to http://localhost:3000 to view your React application running inside a Docker container.
If your React app uses a different port, update the EXPOSE and docker run commands accordingly.
Modify the Dockerfile to suit your specific project structure and dependencies.
Consider using a .dockerignore file to exclude unnecessary files and directories from being copied into the Docker image.
Feel free to contribute to this repository by opening issues or creating pull requests. Happy Dockerizing!
