How does Docker know when to use the cache during a build and when not?
<p>I'm amazed at how good Docker's caching of layers works but I'm also wondering how it determines whether it may use a cached layer or not.</p>

<p>Let's take these build steps for example:</p>

<pre><code>Step 4 : RUN npm install -g   node-gyp
 ---&gt; Using cache
 ---&gt; 3fc59f47f6aa
Step 5 : WORKDIR /src
 ---&gt; Using cache
 ---&gt; 5c6956ba5856
Step 6 : COPY package.json .
 ---&gt; d82099966d6a
Removing intermediate container eb7ecb8d3ec7
Step 7 : RUN npm install
 ---&gt; Running in b960cf0fdd0a
</code></pre>

<p>For example how does it know it can use the cached layer for <code>npm install -g node-gyp</code> but creates a fresh layer for <code>npm install</code> ? </p>