基于Rocky Linux 9镜像构建Python二进制

概述

基于 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

# 设置国内 DNF 镜像源(阿里云)
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

# 下载并解压 Python 源码
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}

# 编译安装 Python
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

# 设置国内 DNF 镜像源
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

# 复制编译好的 Python
COPY --from=builder ${PYTHON_PREFIX} ${PYTHON_PREFIX}

# 设置环境变量
ENV PATH=${PYTHON_PREFIX}/bin:$PATH

# 测试 python 版本
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