Skip to content

Instantly share code, notes, and snippets.

@johnoscott
Last active March 31, 2018 10:54
Show Gist options
  • Save johnoscott/df26d4e106c3aa9cc53cf1a8fdf6b297 to your computer and use it in GitHub Desktop.
Save johnoscott/df26d4e106c3aa9cc53cf1a8fdf6b297 to your computer and use it in GitHub Desktop.

Dockerize a React App in 2018 with CreateReactApp

TLDR

Markdown Less Pretty
Still renders nicely
1 2 3

References

  1. http://mherman.org/blog/2017/12/07/dockerizing-a-react-app/#.Wr8-N9NuaOF

Prerequisites

  1. Create React App

Create the React App

$ npx create-react-app docker101-create-react-app
$ cd docker101-create-react-app

Docker

Add a Dockerfile to the project root

$ touch Dockerfile

and copy the contents.

WARNING note the use of the --silent NPM option. Turn this off if you need to debug the npm install

# base image
FROM node:9.6.1

# set working directory
RUN mkdir /usr/src/app
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
COPY package.json /usr/src/app/package.json
RUN npm install --silent
RUN npm install react-scripts@1.1.1 -g --silent

# start app
CMD ["npm", "start"]

Add a .dockerignore file

This will speed up the Docker build process.

$ echo "node_modules" >> .dockerignore

Build and Tag the Docker Image

$ docker build -t sample-app .

Confirm the build is present on the local machine

$ docker image ls
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
sample-app                  latest              9a8f17ef7f2d        2 minutes ago       980MB

Run bash to see the files in the container image

The last command (sw-precache) is to show that executables in /node_modules/.bin are indeed on the $PATH and can be run.

$ docker container run -it sample-app bash
root@1c8742f38010:/usr/src/app# ls
node_modules  package-lock.json  package.json

root@1c8742f38010:/usr/src/app# du -sh node_modules/
197M	node_modules/

root@1c8742f38010:/usr/src/app# sw-precache
Total precache size is about 126 MB for 20398 resources.
service-worker.js has been generated with the service worker contents.

root@1c8742f38010:/usr/src/app# exit

Run the Container

$ docker container run -it -p 3000:3000 react:app

$ docker run -it \
  -v ${PWD}:/usr/src/app \
  -v /usr/src/app/node_modules \
  -p 3000:3000 \
  --rm \
  sample-app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment