# Step 0
# ---- Base Node ----
FROM node:10-alpine AS base

LABEL maintainer="Zen <nggiang12@gmail.com>"

ENV NODE_ENV=production
# set working directory
RUN mkdir /app
WORKDIR /app
# copy project file
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+) # Only run npm install if these files change.
COPY package*.json ./

# Step 1
# ---- Dependencies ----
FROM base AS dependencies
# install system dependencies
# --no-cache: download package index on-the-fly, no need to cleanup afterwards
RUN apk --no-cache add \
    python \
    make \
    g++
# install production node packages
RUN npm set progress=false && npm config set depth 0
RUN npm install --only=production 
# copy production node_modules aside
RUN cp -R node_modules prod_node_modules
# install ALL node_modules, including 'devDependencies'
RUN npm install --only=dev

# Step 2 & 3
# ---- Build & Test ----
# run linters, setup and tests
FROM base AS built
ENV NODE_ENV=test
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .
# build the app to ./built dir
RUN npm run build
RUN npm run test

# Final Image
# ---- Release ----
FROM base AS release
# copy production node_modules
COPY --from=dependencies /app/prod_node_modules ./node_modules
# copy built
COPY --from=built /app/built ./built
# copy runtime config
COPY ./config ./config

CMD ["npm", "start"]
