naimulhaque.com

February 19th, 2024

Dockerfile for React apps built with Vite

A Dockerfile example for building React apps with Vite and serving them using Nginx.

FROM node:alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
 
FROM nginx:1.17.8-alpine
COPY --from=builder /app/dist /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY ./nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Let's place the nginx.conf file at the root of the project

server {
  listen 80;
  listen [::]:80;
  gzip on;
  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    # to redirect all the requests to index.html,
    # useful when you are using react-router
    try_files $uri /index.html;
  }
}

Let's build the Docker Image and run the container

# Build the docker image
docker build . -t react-vite-docker-example
 
# Run the container
docker run -p 3000:80 react-vite-docker-example