[英]Reduce dimension of Docker Python Image
I'm building a Python Image in Docker and I need it to be the smaller possible.我正在 Docker 中构建一个 Python 图像,我需要它尽可能小。
I'm using venv on my PC and the app is basically a unqiue file.py of 3.2kb.我在我的电脑上使用 venv,该应用程序基本上是一个 3.2kb 的 unqiue file.py。 I'm using Python 3.10 and the following libraries我正在使用 Python 3.10 和以下库
import feedparser
import sched
import time
import dbm
import paho.mqtt.client as mqtt
import json
import logging
My current Dockerfile looks like我现在的 Dockerfile 看起来像
FROM python:3.10.9-alpine3.17
WORKDIR /app
COPY *.py ./
COPY *.txt ./
RUN pip install -r requirements.txt
ENTRYPOINT ["python3"]
CMD ["./main.py"]
And the final image is about 60Mb.最终图像约为 60Mb。 Now, I'm seeing that Python Alpine image is about 20/30Mb and the folder containing my project is about 22Mb.现在,我看到 Python Alpine 图像大约为 20/30Mb,包含我的项目的文件夹大约为 22Mb。
Is there a way to strip even more the dimension of the Docker Image I'm creating, maybe clearing cache after the building or installing only the necessary package?有没有办法去除我正在创建的 Docker 图像的更多尺寸,也许在构建后清除缓存或仅安装必要的 package?
In your pip
command, add the --no-cache-dir
flag to disable writing files to a cache:在您的pip
命令中,添加--no-cache-dir
标志以禁止将文件写入缓存:
RUN pip install --no-cache-dir -r requirements.txt
You can purge the cache:您可以清除缓存:
RUN pip install -r requirements.txt && pip cache purge
Additionally there are some bundled wheel files for bootstrapping ensurepip
in the alpine image which are useless, since pip/setuptools are already installed.此外,还有一些捆绑的 wheel 文件用于在 alpine 图像中引导ensurepip
,这些文件是无用的,因为 pip/setuptools 已经安装。 If you don't need to create venvs within the container, you could unlink those wheels and save another ~3.3 MB:如果您不需要在容器内创建 venvs,您可以取消链接这些轮子并节省另一个 ~3.3 MB:
$ docker run --rm -it python:3.10.9-alpine3.17 ls -l '/usr/local/lib/python3.10/ensurepip/_bundled/'
total 3212
-rw-r--r-- 1 root root 0 Dec 8 01:27 __init__.py
drwxr-xr-x 2 root root 4096 Dec 8 01:27 __pycache__
-rw-r--r-- 1 root root 2051534 Dec 8 01:27 pip-22.3.1-py3-none-any.whl
-rw-r--r-- 1 root root 1232695 Dec 8 01:27 setuptools-65.5.0-py3-none-any.whl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.