如何在 Dockerfile 中预编译 Python 代码

为了在 Dockerfile 中预编译 Python 代码,你可以使用 compileall 模块。如果你想避免在运行时编译 Python 代码的开销,这很有用:

dockerfile_precompile.Dockerfile
RUN python -m compileall /app

完整示例

以下是一个预编译 Python 代码的 Dockerfile 示例:

dockerfile_full_example.Dockerfile
FROM python:3.12

WORKDIR /app

COPY . .

RUN python -m compileall /app

CMD ["python", "app.py"]

Check out similar posts by category: Python, Docker, Container