DEV Community

Cover image for Dockerizing a React Project with Nginx
Krisha Arya
Krisha Arya

Posted on

Dockerizing a React Project with Nginx

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
    β”œβ”€β”€ ...
Enter fullscreen mode Exit fullscreen mode

🧱 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;"]
Enter fullscreen mode Exit fullscreen mode

πŸ”Ž 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 .
Enter fullscreen mode Exit fullscreen mode

βœ… 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
Enter fullscreen mode Exit fullscreen mode

🌐 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 
Enter fullscreen mode Exit fullscreen mode

Then kill the process:

  sudo kill -9 <PID>
Enter fullscreen mode Exit fullscreen mode

or, you can also do so by doing this:

docker ps
Enter fullscreen mode Exit fullscreen mode

This will show all running containers then copy its container id and run below command to stop that container.

docker stop <container-id>
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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>
Enter fullscreen mode Exit fullscreen mode

βœ… 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)