概述
基于 Rocky Linux 9 基础镜像构建 Python 二进制的 Dockerfile,具备以下特性:
- 多阶段构建,最终镜像精简
- 可传入 Python 版本构建,支持默认版本
- 使用阿里云镜像加速 DNF 包源与 Python 源码下载
Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| FROM rockylinux:9 AS builder
ARG PYTHON_VERSION=3.9.23
ENV PYTHON_PREFIX=/opt/python \ PYTHON_TARBALL=Python-${PYTHON_VERSION}.tar.xz \ PYTHON_SRC_DIR=/usr/src/python
RUN sed -i 's|^mirrorlist=|#mirrorlist=|g; s|^#baseurl=http://mirror.centos.org|baseurl=https://mirrors.aliyun.com/rocky|g' /etc/yum.repos.d/*.repo \ && dnf clean all && dnf makecache
RUN dnf install -y \ gcc make zlib-devel bzip2 bzip2-devel readline-devel sqlite-devel \ openssl-devel libuuid-devel libffi-devel wget tar xz-devel curl-devel \ gdbm-devel db4-devel libpcap-devel \ && dnf clean all
RUN mkdir -p ${PYTHON_SRC_DIR} && cd ${PYTHON_SRC_DIR} \ && curl -O https://mirrors.aliyun.com/python-release/source/${PYTHON_TARBALL} \ && tar -xJf ${PYTHON_TARBALL}
RUN cd ${PYTHON_SRC_DIR}/Python-${PYTHON_VERSION} \ && ./configure --prefix=${PYTHON_PREFIX} --enable-optimizations --with-ensurepip=install \ && make -j$(nproc) \ && make install
FROM rockylinux:9
ARG PYTHON_VERSION=3.9.23 ENV PYTHON_PREFIX=/opt/python
RUN sed -i 's|^mirrorlist=|#mirrorlist=|g; s|^#baseurl=http://mirror.centos.org|baseurl=https://mirrors.aliyun.com/rocky|g' /etc/yum.repos.d/*.repo \ && dnf clean all && dnf makecache
COPY --from=builder ${PYTHON_PREFIX} ${PYTHON_PREFIX}
ENV PATH=${PYTHON_PREFIX}/bin:$PATH
CMD ["python3", "--version"]
|
构建命令
默认使用 3.9.23:
1
| docker build -t mypython:3.9.23 .
|
指定其他版本(如 3.11.9):
1
| docker build --build-arg PYTHON_VERSION=3.11.9 -t mypython:3.11.9 .
|
说明
| 部分 |
说明 |
| 多阶段构建 |
构建镜像 builder 编译完 Python 后,精简运行阶段 |
dnf 源替换 |
替换为 阿里云镜像 |
| Python 源码 |
来自阿里云镜像 https://mirrors.aliyun.com/python-release/source/ |
| 默认版本 |
可通过 ARG 配置,默认 3.9.23 |