Avoiding Dependencies Reinstall When Building NodeJS Docker Image
When I first started writing Dockerfile for building a NodeJS app, I will do:
|
|
Sure, this is very simple, but every time a change in the source file, the entire dependency tree needs to be re-installed. The only time you need to rebuild is when package.json
changes.
One trick is to move package.json
elsewhere, and build the dependencies, then move back:
|
|
However, if there are a lot of depending packages with lots of files, the last step will take a long time.
How about using symbolic link to shorten the time?
|
|
Well, it works, but not every NPM package is happy about it. Some will complain about the softlink, result in errors.
So, how can we reuse caches as much as possible, and:
- Do not need to reinstall dependencies
- Do not use symbolic link
Here is a solution, just move down the COPY
statement:
|
|
With this configuration, if package.json
stays the same, only the last cache layer will be rebuilt when source codes change.