跳到主要内容

Build Optimization

Order layers

可以藉由把不常改變的layer且沒有depend on 前面layer的步驟放在前面。甚至也可以把常修改的檔案和不常修改的檔案分開加入,讓不常修改檔案的layer可以一直被cache,例如把lock file和程式碼分開加入,這樣如果dependencies 沒有改變,就可以cache起來。 ex:

# syntax=docker/dockerfile:1
FROM node
WORKDIR /app
COPY . . # Copy over all files in the current directory
RUN npm install # Install dependencies
RUN npm build # Run build

Keep layers small

不要include不需要的檔案來讓layer的size小一點,也可以藉由.dockerignore來exclude不需要的檔案。另外也不要裝不需要的dependencies,可以藉由multi-stage build把local dev image和production image分開,就可以在production image裝不需要的dependencies。

Use the dedicated RUN cache

可以把RUN command的結果cache起來,這樣就不用每次都從網路拉下來。ex:

RUN \
--mount=type=cache,target=/var/cache/apt \
apt-get update && apt-get install -y git

Use multi-stage builds

把build分成數個stage,這樣不僅可以讓build出來的image變小,而且不相依的stage還可以parallel的build,增加build的速度。

Combine commands together wherever possible

如果RUN command可以合併,就寫在同一行讓layer少一點,減少build的時間。