"Create React App" with Docker

john_ryan picture john_ryan · Aug 4, 2016 · Viewed 20k times · Source

I was wondering if anyone had any experience using create-react-app with docker. I was able to get it set up with a Dockerfile like:

from node
RUN mkdir /src
WORKDIR /src
ADD package.json /src/package.json
RUN npm install
EXPOSE  3000
CMD [ "npm", "start" ]

And then used a docker-compose file like:

app:
  volumes:
    - "./app:/src"
  ports:
    - "3000:3000"
    - "35729:35729"
  build: ./app

This allowed me to start up the container and view the app. However livereload didn't work when saving files in the mounted volume and webpack created several .json.gzip files in the src directory.

Any suggestions for getting this working correctly?

Answer

metakermit picture metakermit · Jan 11, 2017

Yeah, as aholbreich mentioned, I'd use npm install / npm start locally on my machine for development, just because it's so easy. It's probably possible with docker-compose, mounting volumes etc. too, but I think it could be a bit fiddly to set up.

For deployment you can then very easily use a Dockerfile. Here's an example Dockerfile I'm using:

FROM node:6.9

# Create app directory
RUN mkdir -p /src/app
WORKDIR /src/app

# to make npm test run only once non-interactively
ENV CI=true

# Install app dependencies
COPY package.json /src/app/
RUN npm install && \
    npm install -g pushstate-server

# Bundle app source
COPY . /src/app

# Build and optimize react app
RUN npm run build

EXPOSE 9000

# defined in package.json
CMD [ "npm", "run", "start:prod" ]

You need to add the start:prod option to your package.json:

"scripts": {
  "start": "react-scripts start",
  "start:prod": "pushstate-server build",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
},

You can run the tests on your CI service with:

docker run <image> npm test

There's nothing stopping you from running this docker container locally as well to make sure things work as expected.