Search code examples
pythonpython-3.xdockerdockerfilealpine-linux

Reduce dimension of Docker Python Image


I'm building a Python Image in Docker and I need it to be the smaller possible.

I'm using venv on my PC and the app is basically a unqiue file .py of 3.2kb. I'm using Python 3.10 and the following libraries

import feedparser
import sched
import time
import dbm
import paho.mqtt.client as mqtt
import json
import logging

My current Dockerfile looks like

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. Now, I'm seeing that Python Alpine image is about 20/30Mb and the folder containing my project is about 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?


Solution

  • 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. If you don't need to create venvs within the container, you could unlink those wheels and save another ~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