# Install dependencies only when needed
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./ 
RUN npm ci

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
ENV NODE_ENV production
WORKDIR /app
# Copy dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN npm run build

# Bundle static assets with nginx
FROM node:16-alpine as production
# Copy built assets from builder
WORKDIR /app
COPY --from=builder /app/build .

# Expose ports
EXPOSE 3000

COPY .env.production .

ENV NODE_ENV production
ENV USER_NAME=node_user USER_UID=2000 GROUP_NAME=node_group GROUP_UID=2000

RUN npm i -g serve \
    && deluser --remove-home node \
    && addgroup --g ${GROUP_UID} -S ${GROUP_NAME} \ 
    && adduser -D -S -s /sbin/nologin -u ${USER_UID} -G ${GROUP_NAME} ${USER_NAME}\
    && chown -R ${USER_NAME}:${GROUP_NAME} "/app/"


USER "${USER_NAME}"
CMD serve -s .