构建定制的Python基础镜像包

场景

工作中经常遇到需要Python镜像包,然后加载一些依赖包,这些依赖包如果使用外面的源下载,构建镜像包比较耗时。将Python镜像包 和 依赖包做成基础镜像,然后放在私有Haror仓中,能够加快构建镜像包的速度。

构建基础镜像包

# Dockerfile
# 优化后的基础镜像(custom-python:3.10)
FROM python:3.10-slim-bullseye

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    libpq-dev gcc musl-dev && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 移除 EXPOSE 和 CMD
# 子镜像 Dockerfile(继承 custom-python:3.10)
FROM 172.171.15.104/common/custom-python:3.10
WORKDIR /

# Set environment variables
ENV PYTHONIOENCODING=utf-8

COPY ./requirements.txt /requirements.txt

RUN  pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

COPY . /

CMD ["gunicorn", "app:app", "-c", "./gunicorn/config.py"]
# requiremet.txt
flask==2.0.3
gevent==22.8.0
greenlet==1.1.3
gunicorn==20.1.0
loguru==0.7.2
numpy==1.23.5  # 兼容 Python 3.10
pandas==1.5.3   # 兼容 Python 3.10
werkzeug==2.0.3

执行
docker build -t custom-python:3.10 .

导出镜像

docker save -o custom-python.tar docker.io/library/custom-python:3.10

加载镜像并导入私仓

docker load -i custom-python.tar
docker tag docker.io/library/custom-python:3.10 hub.pmlabs.com.cn/common/custom-python:3.10
docker push hub.pmlabs.com.cn/common/custom-python:3.10
posted @ 2025-04-03 16:27  左青虫右白鼠  阅读(162)  评论(0)    收藏  举报