DEV Community

loading...

A production-ready Docker image for React

fitiavana07 profile image Fitiavana Ramanandafy ・1 min read

I made this Docker image so I can reuse it easily with every React project I dockerize or start from scratch. I open-sourced it so everyone can use it to move their app easily to production. Here is the GitHub URL: https://github.com/fitiavana07/docker-react.

How do I use it?

Just copy this into a new Dockerfile.

# The first image is for compiling the client files, the second is for serving.

# BUILD IMAGE
FROM node:14-alpine as build-stage

WORKDIR /app

# Install dependencies
COPY package*.json ./
RUN npm install

# Build
COPY . .
RUN npm run build

# -----------------------------------------------------------------------------
# SERVING IMAGE
FROM fitiavana07/nginx-react

# Copy built files
COPY --from=build-stage /app/build /usr/share/nginx/html

# 80 for HTTP
EXPOSE 80

# Run nginx
CMD nginx -g 'daemon off;'
Enter fullscreen mode Exit fullscreen mode

The stack

I used Nginx to serve the built files, along with the config for serving React properly. The whole is bundled into the docker image fitiavana07/nginx-react, so you don't need to worry about the config.

Does it support react-router?

Yes, it supports react-router. All routes other than the root are handled properly.

Suggestions are welcome.

Discussion (2)

pic
Editor guide
Collapse
pjotre86 profile image
pjotre86

Hey. Thanks for sharing this. It would be even better if the docker image is designed to use a non-root user. Especially when you want to consider it a "production" image.
See here, for instance: medium.com/@mccode/processes-in-co...

Collapse
fitiavana07 profile image
Fitiavana Ramanandafy Author

Hey. Thank you for the feedback. I'll check it.