Improving caching
Our Dockerfile is pretty solid in the meantime, but as in every build process, time matters and we could improve a minor thing. Docker is able to cache already done steps and therefore it tries to find out if something has changed during the last build. This is done layer by layer. Currently, it would rebuild everything when something in our Dockerfile changes.
As our build process mainly consists of downloading dependencies, we could improve this a bit in a way that we first only copy the files that define which dependencies are used (package.json and package.lock), run the download process and afterward copy the rest to the container. Let's change our Dockerfile accordingly:
FROM node:22 AS builder
RUN mkdir /app
COPY /app/package*.json /app/
WORKDIR /app
RUN npm install
COPY /app /app
# Our Runtime Container
FROM gcr.io/distroless/nodejs22-debian12
COPY --chown=nonroot:nonroot --from=builder /app /app
RUN chown -R nonroot:nonroot /app
USER nonroot
CMD [ "/app/app.js" ]
With these minor changes, the npm install command should only run when nothing is in the cache or something in the dependency configuration changed.
Feel free to rebuild the container and restart your deployment:
docker compose stop
docker compose build --no-cache
docker compose up
You optimized the build process a bit. Although this might not have a big impact in this lab, such optimizations can save you lots of time in real-world scenarios
