Docker how to run pip requirements.txt only if there was a change?

前端 未结 3 1007
滥情空心
滥情空心 2020-12-02 05:39

In a Dockerfile I have a layer which installs requirements.txt:

FROM python:2.7
RUN pip install -r requirements.txt

When I bui

相关标签:
3条回答
  • 2020-12-02 06:13

    Alternatively as a quicker means to run requirements.txt file without typing "yes" to confirm installation of libraries, you can re-write as:

    COPY requirements.txt ./
    RUN pip install -y -r requirements.txt
    COPY ./"dir"/* .
    
    0 讨论(0)
  • 2020-12-02 06:20

    This is directly mentioned in Docker's own "Best practices for writing Dockerfiles":

    If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This will ensure that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.

    For example:

    COPY requirements.txt /tmp/
    RUN pip install --requirement /tmp/requirements.txt
    COPY . /tmp/
    

    Results in fewer cache invalidations for the RUN step, than if you put the COPY . /tmp/ before it.

    0 讨论(0)
  • 2020-12-02 06:29

    I'm assuming that at some point in your build process, you're copying your entire application into the Docker image with COPY or ADD:

    COPY . /opt/app
    WORKDIR /opt/app
    RUN pip install -r requirements.txt
    

    The problem is that you're invalidating the Docker build cache every time you're copying the entire application into the image. This will also invalidate the cache for all subsequent build steps.

    To prevent this, I'd suggest copying only the requirements.txt file in a separate build step before adding the entire application into the image:

    COPY requirements.txt /opt/app/requirements.txt
    WORKDIR /opt/app
    RUN pip install -r requirements.txt
    COPY . /opt/app
    # continue as before...
    

    As the requirements file itself probably changes only rarely, you'll be able to use the cached layers up until the point that you add your application code into the image.

    0 讨论(0)
提交回复
热议问题