# Dockerレイヤーcacheの解説: CIでのより速いイメージbuild

> Dockerはイメージをcacheされたレイヤーでbuildし、変更のないものを再利用して作業を省く。レイヤーcacheの仕組みと、hitのためのDockerfileの並べ方を学ぼう。

Source: https://latchkey.dev/ja/learn/ci-cd-concepts/docker-layer-caching-explained  
Updated: 2026-06-25

Dockerはイメージをcacheされたレイヤーの積み重ねとしてbuildする。めったに変わらない部分が先に来るようDockerfileを並べれば、ほとんどのbuildがほぼすべてを再利用する。

Dockerfileの各命令はレイヤーを生成する。入力が変わっていなければ、Dockerは前のbuildのレイヤーを再利用できる - だが1つの早期の変更が、その後のすべてを無効化する。並べ順がすべてだ。

## レイヤーがどうcacheされるか

Dockerは各命令とその入力をhashする。hashがcacheされたレイヤーに一致すれば、stepを再実行せずにそれを再利用する。あるレイヤーの入力が変わった瞬間、そのレイヤーとその下のすべてのレイヤーが再buildされる - cacheは選択的にではなく、下方向に無効化される。

## cache hitのために並べる

安定した命令を先に、変わりやすいものを最後に置く。依存関係のマニフェストをcopyし、アプリケーションのsourceをcopyする*前*に依存関係をインストールして、コード変更が依存関係インストールのレイヤーを壊さないようにする。

```Cache-friendly ordering
COPY package*.json ./
RUN npm ci          # cached unless deps change
COPY . .            # changes often; only this layer rebuilds
RUN npm run build
```

## CIがcacheをよく外す理由

- エフェメラルrunnerは、実行ごとにローカルのイメージcacheなしで始まる。
- 外部cacheバックエンドが設定されておらず、何も復元されない。
- depsをインストールする前にsourceをcopyし、commitごとにdepsを無効化する。
- ファイル上部近くの変わるbuild argumentがすべてを壊す。

## CI実行をまたぐcache

エフェメラルrunnerにはローカルcacheがないため、外部cacheが必要だ: BuildKitのregistryバックのcache(`--cache-from` / `--cache-to`)はレイヤーをregistryに保存し、次の実行がそれらを復元する。それなしでは、あらゆるCIのbuildは事実上cold buildだ。

## FAQ

### What is Docker layer caching Explained: faster image builds in CI?

Each instruction in a Dockerfile produces a layer. Docker can reuse a layer from a previous build if its inputs are unchanged - but a single early change invalidates everything after it. Ordering is everything.

### How layers are cached?

Docker hashes each instruction and its inputs. If the hash matches a cached layer, it reuses it instead of re-running the step. The moment one layer’s inputs change, that layer and every layer below it are rebuilt - the cache is invalidated downward, not selectively.

### Order for cache hits?

Put stable instructions first and volatile ones last. Copy your dependency manifest and install dependencies *before* copying your application source, so a code change does not bust the dependency-install layer.

### Caching across CI runs?

Because ephemeral runners have no local cache, you need an external one: BuildKit’s registry-backed cache (--cache-from / --cache-to) stores layers in a registry so the next run restores them. Without that, every CI build is effectively a cold build.

---

Latchkey runs CI/CD that repairs its own failures. Agent entry points: https://latchkey.dev/agent.txt, https://latchkey.dev/openapi.json, https://latchkey.dev/llms.txt
