This documentation outlines how to Dockerize a React application and serve it using Nginx, exposing the app on port 8000 using Docker.
π Project Structure
Assume the folder structure looks like:
educart_docker/
βββ EduCart/
βββ public/
βββ src/
βββ package.json
βββ ...
π§± Step-by-Step Dockerization
1. π§ Create a Dockerfile
Inside the React project folder (e.g., EduCart
), create a Dockerfile
with the following content:
# Step 1: Build React App
FROM node:18 AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Step 2: Serve with Nginx
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
π This creates a production-ready build of your React app and serves it with Nginx inside the container.
2. βοΈ Build the Docker Image
Run this command from the project directory containing Dockerfile:
docker build -t educart-frontend .
β This builds your Docker image and tags it as
educart-frontend
.
3. π Run the Docker Container
Run your container and map it to port 8000
:
docker run -p 8000:80 educart-frontend
π Visit your app at:
http://localhost:8000
π οΈ Troubleshooting
-
ERR_EMPTY_RESPONSE or blank page: Make sure your
build
folder was generated and contains files. - Port already in use? Run:
sudo lsof -i :8000
Then kill the process:
sudo kill -9 <PID>
or, you can also do so by doing this:
docker ps
This will show all running containers then copy its container id and run below command to stop that container.
docker stop <container-id>
π Final Summary: All Docker Commands
# Step into your frontend folder
cd EduCart
# Create Dockerfile (as shown above)
# Build Docker image
docker build -t educart-frontend .
# Run Docker container on localhost:8000
docker run -p 8000:80 educart-frontend
# (Optional) Check what's using port 8000
sudo lsof -i :8000
# (Optional) Kill process using port 8000
sudo kill -9 <PID>
#(Optional) Check what's using port 8000
docker ps
#(Optional) stop container using port 8000
docker stop <container-id>
β Conclusion
Youβve successfully dockerized your React project using multi-stage builds and Nginx for production serving. You can now deploy this image on any server or cloud platform.
Top comments (0)