How to set up React JS project in Docker
Today in this article we will see how we can set up our React JS project in Docker. So those who don’t know what docker is
Docker is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly. With Docker, you can manage your infrastructure in the same ways you manage your applications. By taking advantage of Docker’s methodologies for shipping, testing, and deploying code quickly, you can significantly reduce the delay between writing code and running it in production
Requirements
Step 1: Create a React App
First, we will need to set up a React JS project on our machine. So Open your terminal in your preferred directory and run the below command.
npx create-react-app my-docker-app
Step 2: Create Dockerfile
Next, open your project directory and create a file with the name Dockerfile.dev
. This file is used to define the instructions for building the Docker image. After creating the file paste the below code into it.
FROM node:18-alpine
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
# Expose port
EXPOSE 3000
CMD ["npm", "run", "start"]
Step 3: Create dockerignore file
To avoid copying unnecessary files into your container you need to create .dockerignore
file into your project directory and paste the below code into it.
node_modules
npm-debug.log
build
.git
*.md
.gitignore
Step 4: Create Docker Compose File
This file helps us configure our application. We can configure our docker image, application port, etc through this file. Create a file with the name docker-compose.yml
into your project directory and paste the below code
version: '3'
services:
web:
stdin_open: true
image: docker-react-app-image
build:
context: .
dockerfile: Dockerfile.dev
ports:
- '3000:3000'
volumes:
- ./src:/app/src
Step 5: Running the Docker Image
To run the docker image open your terminal inside your project directory and run the below code into it
docker compose up -d
This command will create your docker image and container and start the application in the port which we have defined in our docker-compose.yml
file. If you have a docker desktop (GUI) installed on your machine you can check that it’s running fine or you can run the below command to check all running docker images in your machine.
docker ps
Now you can visit http://localhost:3000/
to see that your react application is running fine on port 3000 in your browser.
To stop the docker container you can run the below command where [CONTAINER ID] is your container id which you can find running the above command docker ps
docker stop [CONTAINER ID]
That’s it for today below you can find the sample GitHub Repository.
For any query, you can get in touch with me via LinkedIn