Skip to content

Instantly share code, notes, and snippets.

@d3vAdv3ntur3s
Created July 31, 2021 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3vAdv3ntur3s/88b0ef2807f8e088ac72dd79315f1072 to your computer and use it in GitHub Desktop.
Save d3vAdv3ntur3s/88b0ef2807f8e088ac72dd79315f1072 to your computer and use it in GitHub Desktop.
Dockerise React with NGNIX
# Stage 1 - Install dependencies & build react assets
FROM node:14-alpine@sha256:0c80f9449d2690eef49aad35eeb42ed9f9bbe2742cd4e9766a7be3a1aae2a310 AS build
WORKDIR /usr/src/app
ENV NODE_ENV=production
COPY package*.json /usr/src/app/
RUN npm i -g npm@7.20.0
# mount a secret i.e. a custom nprc for private repos to be used for the npm clean install command only
RUN --mount=type=secret,mode=0644,id=npmrc,dst=/usr/src/app/.npmrc npm ci --only-production
COPY ./ /usr/src/app
RUN npm run build-react
# Stage 2 - Serve React assets via NGNIX
FROM nginx:1.21.1-alpine@sha256:23f08ba26a92a00d7368310ab3b4c46907feeebd485f716740e391aa90ad5904
WORKDIR /usr/src/app
COPY --from=build /usr/src/app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
#src: https://gkedge.gitbooks.io/react-router-in-the-real/content/nginx.html
server {
# Nginx to listen to network packets at port 80 on IPv4 only
listen 80 default_server;
# react static assets location
root /usr/share/nginx/html;
index index.html;
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
}
# First attempt to serve request as file, then as directory, then fall back to HTTP response with a 404 status.
# Includes cache expiry defaults for assets
location ~* \.(?:css|js)$ {
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
# Any route containing a file extension (e.g. /devicesfile.js)
location ~ ^.+\..+$ {
try_files $uri =404;
}
# Any route that doesn't have a file extension (e.g. /devices)
location / {
try_files $uri $uri/ /index.html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment