Last active
March 29, 2024 19:09
-
-
Save K-Mistele/96f8368152e6a0051d53fce7da396a3d to your computer and use it in GitHub Desktop.
Use a multi-step build to obtain a smaller final image size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# use a builder for all your dependencies including Typescript compilation | |
FROM node:18.17.1 as builder | |
WORKDIR /opt/app | |
# Install dependencies | |
COPY package*.json . | |
RUN npm install | |
# receive secrets using the --build-arg command e.g. from github actions secrets | |
# and set them as environment variables since next needs them at build time | |
# repeat this as needed for your secrets -> environment variables | |
ARG some_secret | |
ENV SOME_SECRET $some_secret | |
# build the app | |
COPY . . | |
RUN npm run build | |
# set up a runner using a node alpine or node slim image for a smaller final image | |
FROM node:18.17.1-alpine as runner | |
WORKDIR /opt/app | |
# in case you are using runtime environment variables | |
ARG some_secret | |
ENV SOME_SECRET $some_secret | |
# copy over next configurations, build and public folders | |
COPY --from=builder /opt/app/next.config.js ./ | |
COPY --from=builder /opt/app/public ./public | |
COPY --from=builder /opt/app/.next ./.next | |
# copy over your package.json file AND lock file if necessary | |
COPY --from=builder /opt/app/package*.json ./ | |
# only install production dependencies. Make sure you have properly separated your devDependencies in package.json | |
# this is one of the BEST things you can do to reduce your final image size aside from using alpine/slim | |
RUN npm install --production | |
EXPOSE 3000 | |
CMD npm run start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment