如何使码头工人构建也缓存 pip 安装?



我正在使用以下Dockerfile

FROM ubuntu
RUN apt-get update
RUN apt-get install -y 
python3.9 
python3-pip
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 8501
ENTRYPOINT [ "streamlit", "run" ]
CMD ["app.py"]

每当我重建映像时,docker 都会使用以前缓存的映像版本并快速构建它,除非它到达RUN pip install -r requirements.txt部分,每次我重新构建映像时它都会运行(不缓存)。问题是requirements.txt中的一个要求是streamlit==1.9.0,它具有大量的依赖项,因此它减慢了重建过程。长话短说,docker 正在缓存RUN apt-get install foo而不是RUN pip install bar,我想这是意料之中的。当您的文件中有一个长列表时,您将如何找到解决方法来加快映像重建过程requirements.txt

它无法缓存它,因为您在应用程序中的文件不断变化(我猜)。通常的做法是复制需求.txt首先单独复制,然后安装,然后复制其他所有内容。这样,docker 可以根据需要缓存安装.txt没有改变。

FROM ubuntu
RUN apt-get update
RUN apt-get install -y 
python3.9 
python3-pip
WORKDIR /app
COPY requirements.txt . # Copy ONLY requirements. This layer is cached if this file doesn't change
RUN pip install -r requirements.txt # This uses the cached layer if the previous layer was cached aswell
COPY . .
EXPOSE 8501
ENTRYPOINT [ "streamlit", "run" ]
CMD ["app.py"]

Docker BuildKit 最近引入了在构建时挂载。

请参阅 https://github.com/moby/buildkit/blob/master/frontend/dockerfile/docs/syntax.md

有关 PIP 的特定方案,请查看 https://dev.doroshev.com/docker-mount-type-cache/

最新更新