简体   繁体   English

Python docker,我应该通过 pip(在图像内)添加新库并从 pip 冻结创建 requirements.txt,还是手动编辑 requirements.txt?

[英]Python docker, should I add new libraries by pip(within image) and create requirements.txt from pip freeze, or editing the requirements.txt manually?

let's say I am working on a python project with docker.假设我正在使用 docker 开展 python 项目。 using python as the base image.使用 python 作为基础镜像。 Now for new requirements, I need to install another library eg pillow.现在对于新的要求,我需要安装另一个库,例如枕头。 How do I manage it?我该如何管理它?

Run (python-docker) image in interactive mood and use these commands, pip install pillow, pip freeze > requirements.txt.以交互方式运行 (python-docker) 图像并使用这些命令,pip 安装枕头,pip freeze > requirements.txt。 so it will update requirements.txt and also lock the library version.所以它会更新 requirements.txt 并锁定库版本。

Or do I just check the internet for the latest/required pillow library version and manually insert it in requirements.txt?还是我只是在 Internet 上查看最新/所需的枕头库版本并手动将其插入到 requirements.txt 中? Trying to see how developers approach this on docker.试图了解开发人员如何在 docker 上解决此问题。

Could not find anything appropriate on the internet.在互联网上找不到任何合适的东西。 They just have everything required ready beforehand in requirements.txt!他们只是在 requirements.txt 中预先准备好了所有需要的东西!

You should pretty much never run any sort of "install" command in an interactive shell in a container.您几乎不应该在容器中的交互式 shell 中运行任何类型的“安装”命令。 Anything you do in this context will get lost as soon as you exit the container.一旦您退出容器,您在此上下文中所做的任何事情都会丢失。 Similarly, copying files out of a container is inconvenient, validating any updated libraries work is inconvenient, and so on.同样,从容器中复制文件很不方便,验证任何更新的库工作也不方便,等等。

Instead I'd set up an ordinary Python virtual environment相反,我会设置一个普通的 Python 虚拟环境

python3 -m venv venv
. venv/bin/activate

Install your current package set there, install the new (or updated) package, and update the requirements file.安装您当前的 package 设置,安装新的(或更新的)package,并更新需求文件。

pip install -r requirements.txt
pip install pillow
pip freeze > requirements.txt

While you're still in the virtual environment, you can double-check that things still work and see what's exactly changed.当您仍在虚拟环境中时,您可以仔细检查一切是否仍然有效,并查看到底发生了什么变化。

pytest
git diff requirements.txt
./manage.py runserver

If this all works, then you're ready to do an integration test with the updated image.如果这一切正常,那么您就可以使用更新的图像进行集成测试了。

docker build -t my/image .
docker stop my-app
docker rm my-app
docker run -d --name my-app ... my/image

And if that works then you have a change you've validated in two places that you're ready to commit.如果可行,那么您已经在两个地方验证了您准备提交的更改。

git add requirements.txt
git commit -m 'add pillow dependency'

deactivate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM