Skip to content

Instantly share code, notes, and snippets.

@patharanordev
Created September 16, 2023 12:16
Show Gist options
  • Save patharanordev/0f863ebd2ff8d8e3965ed54c97f286e7 to your computer and use it in GitHub Desktop.
Save patharanordev/0f863ebd2ff8d8e3965ed54c97f286e7 to your computer and use it in GitHub Desktop.
Reduce size of Dockerized NestJS from 7XXMB to 185MB
# -------------------------------------------
# Prepare runner
FROM node:18-alpine AS runner
RUN apk update && \
apk add curl bash g++ make && \
rm -rf /var/cache/apk/*
# Install node-prune (https://github.com/tj/node-prune)
RUN curl -sf https://gobinaries.com/tj/node-prune | sh
# Adding nestjs cli to runner not a project
# @nestjs/cli requires in any project.
# You should add it into `devDependency`
# instead of `dependency` in package.json.
RUN npm install -g @nestjs/cli
# -------------------------------------------
FROM runner AS dependencies
WORKDIR /var/www/nest/miniapp-gateway
# For me, some dependency what I need in my organize,
# it need to sync with Bitbucket via SSH key.
# RUN apk add -qU openssh git && \
# mkdir /root/.ssh && \
# chmod 0700 /root/.ssh && \
# ssh-keyscan -t rsa bitbucket.org >> /root/.ssh/known_hosts && \
# echo "$SSH_PRV_KEY" > /root/.ssh/id_rsa && \
# chmod 600 /root/.ssh/id_rsa
# Copy package.json then install all dependency
# excluding `devDependency`.
COPY package*.json .
RUN npm install --only=production
# -------------------------------------------
FROM runner AS builder
WORKDIR /var/www/nest/miniapp-gateway
# Copy dependency from stage `dependencies`.
COPY --from=dependencies /var/www/nest/miniapp-gateway/node_modules ./node_modules
COPY . .
RUN npm run build
# Run node prune
RUN /usr/local/bin/node-prune
# Remove unused source
RUN rm -rf node_modules/rxjs/src/ && \
rm -rf node_modules/rxjs/bundles/ && \
rm -rf node_modules/rxjs/_esm5/ && \
rm -rf node_modules/rxjs/_esm2015/ && \
rm -rf node_modules/swagger-ui-dist/*.map
# -------------------------------------------
# Create new container then copy all output of each stage
FROM node:18-alpine AS production
WORKDIR /var/www/nest/miniapp-gateway
COPY --from=builder /var/www/nest/miniapp-gateway/node_modules ./node_modules
COPY --from=builder /var/www/nest/miniapp-gateway/dist ./dist
# Start your service by using command below :
# $node dist/main.js
# (in this case, it is in entrypoint.sh)
COPY entrypoint.sh .
RUN chmod +x /var/www/nest/miniapp-gateway/entrypoint.sh
CMD ["sh", "entrypoint.sh"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment