1

Running React On Docker

 3 years ago
source link: https://alcher.dev/2021/react-on-docker/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Jan 2, 2021 · John Alcher

react, docker

Running React On Docker

Introduction

This article covers how one could create new React projects and/or run them using Docker.

Prerequisites

In order to follow along, you need to have the following installed in your system:

Try to run the following commands:

$ docker run hello-world
$ make --version

If they ran successfully, then you can continue to the next steps.

Create a new React project

$ mkdir ~/react-project
$ cd react-project 
$ docker run -v $(pwd):/app \
    --rm \
    node:lts-alpine \
    npx create-react-app /app

A fresh React app (created with create-react-app) is now on the ~/react-project directory.

Run a React Project using a Dockerfile and make

Again, given an existing React project at ~/react-project, we can create a Dockerfile:

FROM node:lts-alpine

WORKDIR /app

ENV PATH /app/node_modules/.bin:$PATH

COPY package.json ./
RUN npm install --silent
RUN npm install [email protected] -g --silent

COPY . ./

CMD ["npm", "start"]

..and a Makefile:

build:
    docker build -t yourname/react-project .

start:
    docker run -it --rm -v ${PWD}:/app -v /app/node_modules -p 3000:3000 -e CHOKIDAR_USEPOLLING=true yourname/react-project 

The Makefile should be self-describing. An important detail to understand is the new volume that we attach to the container’s /app/node_modules directory. This allows us to install new npm packages without restarting the container. The flag CHOKIDAR_USEPOLLING allows our React app to use Chokidar’s polling mechanism, which should enable our application’s hot reload feature.

You can now commit these two files with your version control system and run your project in any Docker enabled machine with the following commands:

$ make build
$ make start 

The project should now be served at http://127.0.0.1:3000/

Bonus: adding an ignore file for Docker

In order to speed up the building of our images, we can add a .dockerignore file in the root of our project:

node_modules
build
.dockerignore
Dockerfile

The files and directories above, notably the node_modules directory, would not be sent to the Docker daemon upon building the image.

Example Project

An example React project using the above methodologies is available in this repository.

Additional Reading


Got any feedback or suggestions? Feel free to send me an email or a tweet.
Ciao!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK