Dockerize React App

Rahul Fernando
Towards Dev
Published in
2 min readMay 28, 2022

--

As a developer, you already heard of Docker in your life. If you have no idea about what is Docker and what it use for. I am going to briefly explain it and dockerize simple react application.

Containers

Containers are a technology that allow us to isolate certain kernel processes. Docker container is always running on top of host operating system. Containers contains libraries, binaries and the application itself. Containers do not include a guest operating system, allowing them to be lightweight.

Virtual machines, on the other hand, run on a hypervisor (which is responsible for running virtual machines) and have their own guest operating system.

A Docker container is an image’s runtime instance. You can make numerous containers from a single image.

Images

A Docker image is a collection of files that contain everything needed to run an application as a container. Then this image can deploy to any environment and executable as a container.

Dockerize React App

I assume that you already have docker installed on your local machine. Create a react application using

npx create-react-app react-auth

Let’s get react up and running on our local environment using docker. Open integrated terminal and create file called Dockerfile.dev using

touch Dockerfile.env

Then add below code to it.

# get the base node image
FROM node:alpine as builder

# set the working dir for container
WORKDIR /app

# copy the json file first
COPY ./package.json /app

# install npm dependencies
RUN npm install

# copy other project files
COPY . .

# build the folder
CMD [ "npm", "run", "start" ]

Here we downloads base image from docker hub as the first step, then we define a working directory for our local container, then we copy package.json file and place it in container working directory, as the fourth step we install our npm dependencies, as the fifth step we copy rest of the project files. Then finally we run npm start command to run dev env.

Now we need to define and create our container using doker-compose-local.yml file. In the integrated terminal create file called docker-compose-local.yml using

touch docker-compose-local.yml

Then add below code to it.

version: '3'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
command: npm run start
container_name: app
ports:
- "3000:3000"
volumes:
- ./:/app
- /app/node_modules

Okay, our docker compose file specifies the appearance of our container as well as the port we expose to our host system. Let’s now create a container using this definition.

docker-compose -f docker-compose-local.yml up -d

Finally, the command above will start our react app. You can now use http://localhost:3000 to access your running app.

So, that’s how you dockerize a react app. I hope that this blog post has answered your questions and that you are now able to Dockerize a React App.

--

--