Skip to main content

Dockerfile Template for React.js Framework

This guide helps you create suitable Dockerfile for React.js-based projects.

Key Points for All Dockerfiles

  1. Use official Node.js images
  2. Create a non-root user for enhanced security
  3. Use environment variables for greater flexibility
  4. Optimize for each specific framework
FROM node:$node_version as build

ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o app && \
useradd -g $GID -u $UID -mr -d /home/app -o -s /bin/bash app

USER app
WORKDIR /home/app
COPY --chown=app:app app/ /home/app/

RUN npm install
#CMD [ "npm", "run", "build" ] or CMD [ "npm", "run", "start" ]


FROM nginx:$nginx_version as production

COPY --from=build /home/app/build/ /usr/share/nginx/html/

RUN echo 'server {\n\
listen 3000;\n\
server_name _;\n\
location / {\n\
root /usr/share/nginx/html;\n\
try_files $uri $uri/ /index.html;\n\
}\n\
location /index.html {\n\
root /usr/share/nginx/html;\n\
expires 0d;\n\
}\n\
}' > /etc/nginx/conf.d/default.conf
info
  • React uses /home/app/build for build output path.
  • The Nginx configuration is similar, optimized for SPA applications.
caution
  • Ensure that you replace $node_version and $nginx_version with the appropriate versions.
  • Note that the React build output path (/home/app/build) is different from Vue.js.

Building and Running the Dockerfile

To build the Dockerfile and create an image, use the command:

docker build -t [ProjectName] .
  • -t: Assign a specific tag and name for the project

Then, to run it:

docker run -p outport:inport[3000] --name=container-name -d [ProjectName]
  • -p: Specify the port for running the project
  • outport: External port
  • inport: Internal port of the project specified in the Dockerfile
  • --name: Specify the container name
  • -d: Run the container in detached mode
caution
  1. Security: Always use the latest stable versions of Node.js and Nginx.
  2. Testing: Before deploying to production, make sure to test your Docker image in a production-like environment.