重用Docker映像用于多个python应用程序

时间:2018-07-24 13:20:52

标签: python docker dockerfile

我对整个Docker领域来说还是一个新手。实际上,我正在尝试为不同的python机器学习应用程序建立环境,这些环境应在自己的docker容器中彼此独立运行。由于我不太了解使用基本映像并尝试扩展这些基本映像的方式,因此我为每个新应用程序使用了一个dockerfile,该文件定义了我使用的不同软件包。它们都有一个共同点-它们使用命令 FROM python:3.6-slim 作为基础。

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

File Size for each Docker image

1 个答案:

答案 0 :(得分:2)

在不涉及有关Docker的不同存储后端解决方案的详细信息(请参考Docker - About Storage Drivers)的情况下,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中编写步骤的顺序很重要。

相关问题