首页 > 解决方案 > 为多个 python 应用程序重用 Docker 映像

问题描述

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

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

每个 Docker 映像的文件大小

标签: pythondockerdockerfile

解决方案


在不详细介绍 Docker 的不同存储后端解决方案的情况下(请参阅Docker - 关于存储驱动程序以供参考),docker 会重用映像的所有共享中间点。

话虽如此,即使您在docker images输出中看到[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

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"]

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确实很重要。


推荐阅读