为多个 python 应用程序重用 Docker 镜像

2024-05-06

我对 Docker 的整个世界都很陌生。实际上,我正在尝试为不同的 python 机器学习应用程序建立一个环境,这些应用程序应该在自己的 docker 容器中相互独立地运行。由于我并不真正理解使用基础映像并尝试扩展这些基础映像的方式,因此我为每个新应用程序使用一个 dockerfile,它定义了我使用的不同包。他们都有一个共同点——他们使用命令来自 python:3.6-slim作为基础。

我正在寻找一个起点或方法,可以轻松扩展此基础映像以形成一个新映像,其中包含每个应用程序所需的各个包,以节省磁盘空间。现在,每个图像的文件大小约为。 1GB,希望这可以成为减少数量的解决方案。


无需详细了解 Docker 的不同存储后端解决方案(检查Docker - 关于存储驱动程序 https://docs.docker.com/storage/storagedriver/供参考),docker 重用了镜像的所有共享中间点。

话虽如此,即使你看到docker images output [1.17 GB, 1.17 GB, 1.17 GB, 138MB, 918MB]这并不意味着正在使用您存储中的总和。我们可以这样说:

sum(`docker images`) <= space-in-disk

中的每个步骤Dockerfile创建一个图层。

让我们采用以下项目结构:

├── common-requirements.txt
├── Dockerfile.1
├── Dockerfile.2
├── project1
│   ├── requirements.txt
│   └── setup.py
└── project2
    ├── requirements.txt
    └── setup.py

With Dockerfile.1:

FROM python:3.6-slim
# - here we have a layer from python:3.6-slim -

# 1. Copy requirements and install dependencies
# we do this first because we assume that requirements.txt changes 
# less than the code
COPY ./common-requirements.txt /requirements.txt
RUN pip install -r requirements
# - here we have a layer from python:3.6-slim + your own requirements-

# 2. Install your python package in project1
COPY ./project1 /code
RUN pip install -e /code
# - here we have a layer from python:3.6-slim + your own requirements
# + the code install

CMD ["my-app-exec-1"]

With Dockerfile.2:

FROM python:3.6-slim
# - here we have a layer from python:3.6-slim -

# 1. Copy requirements and install dependencies
# we do this first because we assume that requirements.txt changes 
# less than the code
COPY ./common-requirements.txt /requirements.txt
RUN pip install -r requirements
# == here we have a layer from python:3.6-slim + your own requirements ==
# == both containers are going to share the layers until here ==
# 2. Install your python package in project1
COPY ./project2 /code
RUN pip install -e /code
# == here we have a layer from python:3.6-slim + your own requirements
# + the code install ==

CMD ["my-app-exec-2"]

这两个 docker 镜像将与 python 和 common-requirements.txt 共享层。当构建具有大量繁重库的应用程序时,它非常有用。

为了编译,我会这样做:

docker build -t app-1 -f Dockerfile.1 .
docker build -t app-2 -f Dockerfile.2 .

因此,请考虑如何编写步骤的顺序Dockerfile确实很重要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为多个 python 应用程序重用 Docker 镜像 的相关文章

随机推荐