Search code examples
reactjs.netdockerserver-side-rendering

How to run Dockerized React application in SSR (Server Side Rendering) mode


I have a React application which runs on Docker container and interacts with .NET Core application running on another container. I want to run my React application in SSR (Server Side Rendering) mode. How can I do it? Should I install Nextjs in React application container?


Solution

  • If you want to do server side rendering you have to use a nodejs image for your task.Easiest way to do server side rendering is use of static server.

    example dockerfile for server side rendering:

    FROM node:16 
    
    # Create src directory 
    WORKDIR /usr/src/
    
    RUN npm init
    RUN npm install -g serve
    
    # adding bundle file to working dir
    COPY . ./build
    
    EXPOSE 3000 
    
    # start static server
    RUN serve -s build
    

    If want to do clientside rendering you can build your docker image from nginx. first you have to build your react app. See the following

    example dockerfile for client side rendering :

    FROM nginx:alpine
    
    # adding nginx.conf file to the right place
    COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf
    
    #remove default html file
    RUN rm -rf /usr/share/nginx/html/*
    
    #Copy index.html to nginx/html dir (this is the first thing request by browser)
    COPY --from=builder /react-ui/build /usr/share/nginx/html
    
    EXPOSE 3000 80
    
    ENTRYPOINT ["nginx", "-g", "daemon off;"]