Skip to content
Advertisement

Why use requirements.txt in a Docker image

There is a similar question from last year but I don’t think the responses are widely applicable and it’s not accepted.

Edit: this is in the context of developing small jobs that will only be run in docker in-house; I’m not talking about sharing work with anyone outside a small team, or about projects getting heavy re-use.

What advantage do you see in using requirements.txt to install instead of pip install commands in Dockerfile? I see one: your Dockerfile for various projects is more cookie-cutter.

I’m not even thinking of the use of setup envisioned in the question I linked.

What downside is there to naming the packages in Dockerfile:

 RUN   pip install --target=/build  django==3.0.1 Jinja2==2.11.1 .  . . 

EDIT 2: @superstormer asked “what are the upsides to putting it in Dockefile” — fair question. I read co-workers’ dockerfiles in Gitlab and have to navigate to the requirements, I don’t have it locally in an editor. EDIT3: Note to self: so clone it and look at it in an editor.

Advertisement

Answer

First consider going with the flow of the tools:

  • To manually install those packages, inside or outside a Docker Container, or to test that it works without building a new Docker Image, do pip install -r requirements.txt. You won’t have to copy/paste the list of packages.
  • To “freeze” on specific versions of the packages to make builds more repeatable, pip freeze will create (or augment) that requirements.txt file for you.
  • PyCharm will look for a requirements.txt file, let you know if your currently installed packages don’t match that specification, help you fix that, show you if updated packages are available, and help you update.
  • Presumably other modern IDEs do the same, but if you’re developing in plain text editors, you can still run a script like this to check the installed packages (this is also handy in a git post-checkout hook):
    echo -e "nRequirements diff (requirements.txt vs current pips):"
    diff --ignore-case <(sed 's/ *#.*//;s/^ *--.*//;/^$/d' requirements.txt | sort --ignore-case) 
      <(pip freeze 2>/dev/null | sort --ignore-case) -yB --suppress-common-lines
    

Hopefully this makes it clearer that requirements.txt declares required packages and usually the package versions. It’s more modular and reusable to keep it separate than embed it inside a Dockerfile.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement