无需详细了解 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
确实很重要。