Steps to Dockerize a Vite + React App
1. Create a Dockerfile
Create a file named Dockerfile
in the root of your project with the following content:
# Use an official node image as the base image
FROM node:18-alpine
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
RUN npm install
COPY . .
# Expose the port the app runs on
EXPOSE 5173
# Command to run the application
CMD ["npm", "run", "dev"]`
- Create a
.dockerignore
file Create a .dockerignore file in the root of your project to exclude unnecessary files:
node_modules
npm-debug.log
build
.dockerignore
**/.git
**/.DS_Store
**/node_modules
3. Build the Docker image
Run the following command in your terminal to build the Docker image:
docker build -t vite-react-app .
4. Run the Docker container
After the image is built, run the container using:
docker run -p 5173:5173 vite-react-app
Your Vite + React app should now be accessible at http://localhost:5173
.
5. Give name Docker container and run in detached mode
After the image is built, run the container using:
docker run -d -p 5173:5173 --rm --name vite-react-container vite-react-app
Now if we stop the container it will be deleted automatically.
6. Using Docker Compose
Docker Compose is a tool for defining and running multi-container Docker applications. Here's how to use it with your Vite + React app:
6.1. Create a docker-compose.yml
file
Create a file named docker-compose.yml
in the root of your project with the following content:
version: '3.8'
services:
react-vite-app:
image: react-vite-app
build:
context: .
dockerfile: Dockerfile
ports:
- '5173:5173'
container_name: react-vite-container
stdin_open: true
environment:
- CHOKIDAR_USEPOLLING=true
volumes:
- .:/app
- /app/node_modules
This docker-compose.yml
file sets up a Docker container for a React project built with Vite. It mounts the project directory to /app
for live code updates and ignores /app/node_modules
to prevent conflicts with the host's node_modules
. As a result, any changes in the code will be reflected in the running container at http://localhost:5173
.
6.2. Run the container using Docker Compose
To start your application using Docker Compose, run the following command in your terminal:
docker-compose up
This command will build the image if it doesn't exist and start the container. Your Vite + React app should now be accessible at http://localhost:5173
.
6.3. Stop the container
To stop the container, you can use:
docker-compose down
This will stop and remove the containers defined in your docker-compose.yml
file.
Using Docker Compose provides several advantages, including easier management of environment variables, volume mounting for live code updates, and the ability to define and run multi-container applications.