Dockerize Vite+ReactJS application

This post shows how to dockerize a ReactJS app created with Vite using react-typescript template.

Implementation

In my opinion, the best way to do this goal, is using nginx image

Project config

package.json

"scripts":  {
 "dev":  "vite",
 "build":  "tsc && vite build",
 "serve":  "vite preview"
 },

Folders structure

| --dist
   | --src
   | --.dockerignore
   | --Dockerfile
   | --package.json
   | --package-lock.json
   | --deploy 
   ----| --nginx
   --------| --nginx.config

nginx.config file in folder deploy/nginx

map $sent_http_content_type $expires {
 default                    off;
 text/html                  15m;
 text/css                   15m;
 application/javascript     15m;
 ~image/                    15m;
}
server {

listen 80;
 root   /usr/share/nginx/html;
 index  index.html;
 etag on;
 expires $expires;
 location / {
 try_files $uri @prerender;
 }
 location @prerender {
 proxy_set_header X-Prerender-Token GsMLRmorzgxywljuDowD;

set $prerender 0;
 if ($http_user_agent ~* "googlebot|bingbot|yandex|baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest\/0.|pinterestbot|slackbot|vkShare|W3C_Validator|whatsapp|Screaming Frog SEO Spider") {
 set $prerender 1;
 }
 if ($args ~ "escaped_fragment") {
 set $prerender 1;
 }
 if ($http_user_agent ~ "Prerender") {
 set $prerender 0;
 }
 if ($uri ~* ".(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)") {
 set $prerender 0;
 }

#resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
 resolver 8.8.8.8;

if ($prerender = 1) {

#setting prerender as a variable forces DNS resolution since nginx caches IPs and doesnt play well with load balancing
 set $prerender "service.prerender.io";
 rewrite .* /$scheme://$host$request_uri? break;
 proxy_pass http://$prerender;
 }
 if ($prerender = 0) {
 rewrite .* /index.html break;
 }
 }
 error_page   500 502 503 504  /50x.html;
 location = /50x.html {
 root   /usr/share/nginx/html;
 }
}




Dockerfile

FROM mhart/alpine-node:12 AS builder
WORKDIR /app
COPY . .
RUN yarn install
RUN yarn run build
FROM nginx:1.16.0-alpine
COPY --from=builder /app/dist /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY deploy/nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]




Documentation

27