使用GitHub Actions在Docker构建器中缓存pip依赖项

4
我正在使用 Github Actions 构建 Docker 镜像。我缓存了 Docker 层(这很有效),但有时层不会被重用(不确定原因!我遵循 最佳实践,但忽略了那个问题),我使用备用的 pip 缓存来加速构建。
Dockerfile 很简单:
# syntax=docker/dockerfile:1.2
FROM python:3.10-slim
RUN python -m pip install --upgrade pip &&  pip cache dir
COPY requirements.txt ./
RUN --mount=type=cache,target=/root/.cache/pip/ pip install -r requirements.txt

我正在使用--mount标志来自语法1.2,它“允许构建容器缓存编译器和软件包管理器的目录”。
Github actions缓存(我想将其挂载在构建容器上):
- name: Cache pip
  uses: actions/cache@v3
  with:
    path: /root/.cache/pip
    key: pip-{{ hashFiles('requirements*.txt') }}

和 Docker 构建

- name: Build and push
  uses: docker/build-push-action@v2
  with:
    cache-from: type=gha
    cache-to: type=gha,mode=max

我可以为您提供翻译帮助。以下是需要翻译的内容:

如何将pip缓存挂载到docker builder容器中?

目前,在dockerfile中使用此命令时,缓存为空:

RUN --mount=type=cache,target=/root/.cache/pip/ pip cache info && ls /root/.cache/pip

输出:

19 RUN --mount=type=cache,target=/root/.cache/pip/ pip cache info && ls /root/.cache/pip
#19 0.387 Package index page cache location: /root/.cache/pip/http
#19 0.387 Package index page cache size: 0 bytes
#19 0.387 Number of HTTP files: 0
#19 0.387 Wheels location: /root/.cache/pip/wheels
#19 0.387 Wheels size: 0 bytes
#19 0.387 Number of wheels: 0
#19 DONE 0.4s
1个回答

4

这个方法确实有效,将我的安装时间从180秒降低到了30-40秒,虽然有点奇怪但我已经让它可以同时适用于pip和yarn(不过由于我使用的是yarn 1,而大部分时间都用在了I/O读写上,所以yarn并没有节约时间)。

您需要使用buildx v0.8.0+来支持 --build-context,并且需要使用docker前端语法v1.4+来支持RUN --mount。我还使用github actions cache来处理pip依赖项的安装和缓存。具体如下:

  1. github缓存操作,安装pip依赖项,同时获取pip缓存目录:::set-output name=pip-dir::$(pip cache dir) ,以便后续步骤使用
  2. 我正在使用docker build and push action,它支持--build-context
    build-contexts: pip_cache=${{steps.vars.outputs.pip-dir}}
  3. 更新Docker文件以使用pip_cache构建上下文:
    RUN --mount=type=cache,target=/root/.cache/pip,from=pip_cache pip install -r requirements.txt

在构建时,使用缓存的包进行pip安装:

#22 RUN --mount=type=cache,target=/root/.cache/pip,from=pip_cache pip install -r requirements.txt
#22 0.587 Requirement already satisfied: wheel in /usr/lib/python3/dist-packages (0.34.2)
#22 0.592 WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
#22 1.440 Collecting aenum==2.2.3
#22 1.442   Using cached aenum-2.2.3-py3-none-any.whl (40 kB)
#22 1.495 Collecting alembic==1.7.3
#22 1.498   Using cached alembic-1.7.3-py3-none-any.whl (208 kB)

尽管下载速度很快,但为了节省构建轮子的时间,使用该工具仍然是值得的。


1
你不需要将Docker容器与Github Runner的操作系统保持同步吗?如果能够在容器内安装所需的依赖项,以避免与不同操作系统发生任何问题,那就太好了。 - nickswiss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接