How to reduce docker image size

The above image is a very common joke on NodeJS. But fret not there are already several documentations on how to reduce the size of the node modules. I just want to share the experience that I have reducing the size of the docker image.

The above is the file before the reduction

the above is after the reduction and the below is the effect of the reduction

So what I learn from this exercise:

  1. Don’t use RUN commands unnecessary. Every RUN command adds a layer to the docker image. For my case the npm install command needs to pull library files from a different git repository so I need ssh certificate set up to do a git pull, but that alone adds up the image size even though I remove the .ssh folder later.
  2. Use multi stage docker build to compile/download all the necessary files or libraries in the first stage, then use a completely clean slate docker image and copy the libraries from the first stage of the build to the second stage of the build. This way your image will avoid a lot of unnecessary RUN layers. the command is COPY --from=<first image name> <folder/path/of/first/image> <folder/path/of/second/image>
  3. Use slim or other smaller images (jessie, alpine). There will be missing needed libraries hence do a throughout test and add the needed libraries when error was thrown. Even better start from jessie or alpine OS when build the second image.
  4. Use node-prune, which helps remove irrelevant files from node_modules folder like README.md.

Conclusion

These same principles can be applied to any other programming languae to reduce image size. The principals is just the bare necessities of files and libraries

Cloud and site reliability enthusiasts. AWS SA Associate certified

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store