From d15bebe3724ee80ee995f2bdea34c9c6c8f3c7d0 Mon Sep 17 00:00:00 2001 From: Ilko Kacharov Date: Tue, 16 Feb 2021 08:25:01 +0200 Subject: [PATCH] Reduce docker image size and fine-tune multi-stage builds :whale: --- .dockerignore | 2 ++ Dockerfile | 48 ++++++++++++++++++++++++++++------------------ docker-compose.yml | 2 ++ 3 files changed, 33 insertions(+), 19 deletions(-) diff --git a/.dockerignore b/.dockerignore index 7793d8e42..45b2204e4 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,6 @@ node_modules .next .dockerignore +.github +.git Dockerfile diff --git a/Dockerfile b/Dockerfile index bd9d79329..f89e7a34b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,31 +1,41 @@ -# Pull node image from docker hub -FROM node:14 AS development - -# Set working directory +# Build target dependencies # +########################### +FROM node:14-alpine AS base WORKDIR /app - -ARG NODE_ENV=development - -# Add `/app/node_modules/.bin` to $PATH +ARG NODE_ENV=production ENV PATH=/app/node_modules/.bin:$PATH \ NODE_ENV="$NODE_ENV" - -# Install and cache app dependencies COPY package.json yarn.lock /app/ -RUN cd /app/ && yarn install --production=false - -# Copy existing application directory contents -COPY . /app - EXPOSE 3040 +# Build target dependencies # +########################### +FROM base AS dependencies +# Install prod dependencies +RUN yarn install --production +# Cache prod dependencies +RUN cp -R node_modules /prod_node_modules +# Install dev dependencies +RUN yarn install + +# Build target development # +############################ +FROM dependencies AS development +COPY . /app CMD [ "yarn", "dev" ] +# Build target builder # +######################## +FROM base AS builder +COPY . /app +RUN yarn add --dev typescript @types/node && \ + yarn build && \ + rm -rf node_modules # Build target production # ########################### -FROM development AS production -ARG NODE_ENV=production -WORKDIR /app -RUN yarn build +FROM base AS production +COPY --from=builder /app/.next /app/.next +COPY --from=dependencies /prod_node_modules /app/node_modules +COPY . /app CMD [ "yarn", "start" ] diff --git a/docker-compose.yml b/docker-compose.yml index 9d17b0631..bbc27a33c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,6 +20,8 @@ services: # Local:Container mounting points - ./src:/app/src - ./public:/app/public + - /app/node_modules + - /app/.next environment: API_URL: ${API_URL}