Step By Step Guide To Dockerize React app with vite

Step By Step Guide To Dockerize React app with vite | Dockerize a Vite + React application

In this post, you'll learn how to dockerize your react app created using the Vite tool for the development environment.

Prerequisites

  • Basic knowledge of React

  • Basic understanding of what is docker, check my basic Docker Blog

  • Docker on your local system

Step 1: Create React App Using Vite

npm create vite@latest

Step 2: Update vite.config File

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server : {
    host: true, // needed for the Docker Container port mapping to work
    strictPort: true,
    port: 3000, // you can replace this port with any port

  }
})

Step 3: Create a Dockerfile

Create a file called Dockerfile in the root of your project directory.

FROM node:20-alpine

WORKDIR /app

COPY package.json .

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "run", "dev"]

If you don't know what are these commands, read the explanation 👇

  • FROM node - Will create a node environment in the container

  • WORKDIR /app - Will create a directory app and switch to that directory

  • COPY package.json . - Copies package.json file to /app directory

  • RUN npm i - Runs npm install to create node_modules for your app

  • COPY . . - Copies the source code to /app directory

  • EXPOSE 3000 - Exposes the port to access the app from outside the container i.e from the browser

  • CMD ["npm", "run", "dev"] - Executes npm run dev to start the server

Step 4: Create a .dockerignore file

Create a file called .dockerignore in the root of your project directory.

node_modules
README.md

Step 5: Build the Dockerfile

docker build -t [any name] .

Flag used in the command

  • -t - To tag the container (This will be your container name)

After the build completion, a docker image will be created.

Docker Image is a template to run the container.

To check your Docker Image, execute

docker images

Step 6: Run the Docker Container

docker run -d --rm -p 3000:3000 --name [name of the container] [your docker image name]

Flag used in the command

  • -d - To run the container in the background (Detach Mode )

  • --rm - To delete the container, when you stop the container

  • -p - Port Mapping between the container and the outside world.

  • 3000:3000 - [Port access from Browser]: [Port exposed from the container]

Step 7: Open the App in the Browser

Open the Browser and access localhost:5000

Did you find this article valuable?

Support Shivam Sharma by becoming a sponsor. Any amount is appreciated!