Mastodon hachyterm.io

This post will be my notes on dockerizing a React application.
You can find the original post by Michael Herman at Dockerizing a React App.
I use a dedicated node user in my approach, instead of running the container as root user.
For detailed explanations, go to Michael’s post.

Requirements

  • Docker v19.03
  • docker-compose 1.25
  • Node v12.13.1

Project Setup

Create the application, for example, via create-react-app:

npx create-react-app dockerized-react && cd dockerized-react

Docker

Add a Dockerfile to your project directory (a file without extension):

## base image
FROM node:12.13.1-buster-slim

## set working directory
WORKDIR /usr/src/app

## add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

## install and cache app dependencies
## create user "node" and give permissions
COPY package.json /usr/src/app/package.json
RUN npm install react-scripts@3.2.0 -g --silent
RUN chown -R node:node . && chmod -R 755 .
USER node
RUN npm install --silent
RUN npm cache clean --force

## start app
## see package.json for npm command
CMD ["npm", "run", "start"]

Why Debian Buster instead of Alpine?
Alpine uses a different C library (musl) instead of the commond glibc. That can lead to unexpected problems.
(AFAIK it doesn’t matter for a stand-alone React application, but might cause complications for Node.js.)

Add a .dockerignore file:

node_modules

Docker-compose

Create a file docker-compose.yml in your directory:


version: '3.7'

services:

  dockerized-react:
    container_name: dockerized-react
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - '.:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - '3001:3000'
    environment:
      - NODE_ENV=development

Build and run with: docker-compose up -d --build.

Further Reading