利用python构建Dockerfile 文件

使用 Python 脚本来创建 Dockerfile 可以带来多方面的好处,尤其是当你需要自动化构建过程、管理复杂的构建步骤或者需要根据不同的环境条件生成不同的 Docker 镜像时。以下是使用 Python 创建 Dockerfile 的一些主要优点:
自动化和可重复性:
通过 Python 脚本,你可以自动化 Dockerfile 的生成过程,确保每次构建都是可重复的。这对于持续集成(CI)和持续部署(CD)流程尤为重要。
灵活性和可配置性:
Python 脚本可以根据不同的输入参数或环境变量动态生成 Dockerfile 内容。这意味着你可以为不同的目标平台或配置生成定制化的镜像。
错误检查和验证:
在 Python 脚本中,你可以添加逻辑来验证输入参数的有效性,检查依赖项是否存在,以及其他错误检查机制,从而减少人为错误。
复杂逻辑处理:
对于复杂的构建步骤,Python 脚本可以包含条件语句、循环、函数调用等,使得处理复杂的构建逻辑变得更加容易。
维护和管理:
将 Dockerfile 的生成逻辑封装在 Python 脚本中,使得代码更加易于维护和更新。当构建过程需要变更时,只需修改脚本即可。
集成其他工具:
Python 脚本可以与其他工具和库(如 Git、Docker API、CI/CD 系统等)集成,实现更高级的自动化功能。
版本控制:
通过将生成 Dockerfile 的 Python 脚本放在版本控制系统中,你可以跟踪构建逻辑的变更历史,并在团队中共享。
跨平台兼容性:
使用 Python 脚本生成 Dockerfile 可以在不同的操作系统和环境中工作,因为 Python 是跨平台的。
模板化和代码重用:
你可以编写通用的 Python 函数或类来生成 Dockerfile,这些代码可以用于多个项目,提高代码的重用性。
环境隔离:
在 Python 脚本中,你可以设置不同的环境变量或配置,以生成适用于不同环境(如开发、测试、生产)的 Docker 镜像。

总之,使用 Python 创建 Dockerfile 提供了一种强大、灵活且可维护的方式来管理 Docker 镜像的构建过程。这种方法特别适用于需要高度定制化和自动化的场景。

python 脚本如下:

import argparse
import os

FLAGS = None


def install_new_version_of_TRT(clone_repo=False, trtllm_be_repo_tag="main"):
    df = """
# Remove prevous TRT installation
RUN apt-get remove --purge -y tensorrt* libnvinfer*
RUN pip uninstall -y tensorrt

# Install new version of TRT using the script from TRT-LLM
RUN apt-get update && apt-get install -y --no-install-recommends python-is-python3
"""
    if clone_repo:
        df += """
# FIXME: Update the url
RUN git clone --single-branch --depth=1 -b {} https://github.com/triton-inference-server/tensorrtllm_backend.git
RUN cd tensorrtllm_backend && git submodule update --init --recursive
RUN cp tensorrtllm_backend/tensorrt_llm/docker/common/install_tensorrt.sh /tmp/
RUN rm -fr tensorrtllm_backend
    """.format(trtllm_be_repo_tag)
    else:
        df += """
    COPY tensorrt_llm/docker/common/install_tensorrt.sh /tmp/
    """
    df += """
RUN bash /tmp/install_tensorrt.sh && rm /tmp/install_tensorrt.sh

ENV LD_LIBRARY_PATH=/usr/local/tensorrt/lib/:$LD_LIBRARY_PATH
ENV TRT_ROOT=/usr/local/tensorrt
    """
    return df


def create_postbuild(repo_tag="main"):
    df = """
WORKDIR /workspace
"""
    df += install_new_version_of_TRT(clone_repo=True,
                                     trtllm_be_repo_tag=repo_tag)
    df += """
# Remove TRT contents that are not needed in runtime
RUN ARCH="$(uname -i)" && \
    rm -fr ${TRT_ROOT}/bin ${TRT_ROOT}/targets/${ARCH}-linux-gnu/bin ${TRT_ROOT}/data && \
    rm -fr  ${TRT_ROOT}/doc ${TRT_ROOT}/onnx_graphsurgeon ${TRT_ROOT}/python && \
    rm -fr ${TRT_ROOT}/samples  ${TRT_ROOT}/targets/${ARCH}-linux-gnu/samples

# Uninstall unused nvidia packages
RUN if pip freeze | grep -q "nvidia.*"; then \
        pip freeze | grep "nvidia.*" | xargs pip uninstall -y; \
    fi
RUN pip cache purge

ENV LD_LIBRARY_PATH=/usr/local/tensorrt/lib/:/opt/tritonserver/backends/tensorrtllm:$LD_LIBRARY_PATH
"""
    return df


def dockerfile_for_linux():
    df = """
ARG BASE_IMAGE={}
""".format(FLAGS.trtllm_base_image)
    df += """
FROM ${BASE_IMAGE} as base
WORKDIR /workspace

RUN apt-get update && apt-get install python3-pip -y
COPY requirements.txt /tmp/
RUN pip3 install -r /tmp/requirements.txt --extra-index-url https://pypi.ngc.nvidia.com
"""
    df += install_new_version_of_TRT()
    df += """
FROM base as dev

# CMake
RUN ARCH="$(uname -i)" && wget https://github.com/Kitware/CMake/releases/download/v3.27.6/cmake-3.27.6-linux-${ARCH}.sh
RUN bash cmake-3.27.6-linux-*.sh --prefix=/usr/local --exclude-subdir && rm cmake-3.27.6-linux-*.sh
ENV PATH="/usr/local/bin:${PATH}"

COPY tensorrt_llm/requirements-dev.txt /tmp/
RUN pip install -r /tmp/requirements-dev.txt --extra-index-url https://pypi.ngc.nvidia.com

FROM dev as trt_llm_builder

WORKDIR /app
COPY scripts scripts
COPY tensorrt_llm tensorrt_llm
"""
    df += """
ARG TRTLLM_BUILD_CONFIG={}
""".format(FLAGS.trtllm_build_config)
    df += """
RUN cd tensorrt_llm && python3 scripts/build_wheel.py --build_type=${TRTLLM_BUILD_CONFIG} --trt_root="${TRT_ROOT}" -i --clean

# Copy all artifacts needed by the backend to /opt/tensorrtllm
ARG TRTLLM_BUILD_LIB=tensorrt_llm/cpp/build/tensorrt_llm
RUN mkdir -p /opt/trtllm_lib && \
    cp ${TRTLLM_BUILD_LIB}/libtensorrt_llm.so /opt/trtllm_lib && \
    cp ${TRTLLM_BUILD_LIB}/thop/libth_common.so /opt/trtllm_lib && \
    cp ${TRTLLM_BUILD_LIB}/plugins/libnvinfer_plugin_tensorrt_llm.so \
        /opt/trtllm_lib && \
    cp ${TRTLLM_BUILD_LIB}/plugins/libnvinfer_plugin_tensorrt_llm.so.9 \
        /opt/trtllm_lib && \
    cp ${TRTLLM_BUILD_LIB}/plugins/libnvinfer_plugin_tensorrt_llm.so.9.1.0 \
        /opt/trtllm_lib
"""

    with open(FLAGS.output, "w") as dfile:
        dfile.write(df)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--trtllm-base-image",
        type=str,
        required=True,
        help="Base image for building TRT-LLM.",
    )
    parser.add_argument(
        "--trtllm-build-config",
        type=str,
        default="Release",
        choices=["Debug", "Release", "RelWithDebInfo"],
        help="TRT-LLM build configuration.",
    )
    parser.add_argument("--output",
                        type=str,
                        required=True,
                        help="File to write Dockerfile to.")

    FLAGS = parser.parse_args()

    dockerfile_for_linux()

产生的dockerfile 文件

ARG BASE_IMAGE=nvcr.io/nvidia/tritonserver:23.10-py3-min

FROM ${BASE_IMAGE} as base
WORKDIR /workspace

RUN apt-get update && apt-get install python3-pip -y
COPY requirements.txt /tmp/
RUN pip3 install -r /tmp/requirements.txt --extra-index-url https://pypi.ngc.nvidia.com

# Remove prevous TRT installation
RUN apt-get remove --purge -y tensorrt* libnvinfer*
RUN pip uninstall -y tensorrt

# Install new version of TRT using the script from TRT-LLM
RUN apt-get update && apt-get install -y --no-install-recommends python-is-python3

    COPY tensorrt_llm/docker/common/install_tensorrt.sh /tmp/
    
RUN bash /tmp/install_tensorrt.sh && rm /tmp/install_tensorrt.sh

ENV LD_LIBRARY_PATH=/usr/local/tensorrt/lib/:$LD_LIBRARY_PATH
ENV TRT_ROOT=/usr/local/tensorrt
    
FROM base as dev

# CMake
RUN ARCH="$(uname -i)" && wget https://github.com/Kitware/CMake/releases/download/v3.27.6/cmake-3.27.6-linux-${ARCH}.sh
RUN bash cmake-3.27.6-linux-*.sh --prefix=/usr/local --exclude-subdir && rm cmake-3.27.6-linux-*.sh
ENV PATH="/usr/local/bin:${PATH}"

COPY tensorrt_llm/requirements-dev.txt /tmp/
RUN pip install -r /tmp/requirements-dev.txt --extra-index-url https://pypi.ngc.nvidia.com

FROM dev as trt_llm_builder

WORKDIR /app
COPY scripts scripts
COPY tensorrt_llm tensorrt_llm

ARG TRTLLM_BUILD_CONFIG=Release

RUN cd tensorrt_llm && python3 scripts/build_wheel.py --build_type=${TRTLLM_BUILD_CONFIG} --trt_root="${TRT_ROOT}" -i --clean

# Copy all artifacts needed by the backend to /opt/tensorrtllm
ARG TRTLLM_BUILD_LIB=tensorrt_llm/cpp/build/tensorrt_llm
RUN mkdir -p /opt/trtllm_lib &&     cp ${TRTLLM_BUILD_LIB}/libtensorrt_llm.so /opt/trtllm_lib &&     cp ${TRTLLM_BUILD_LIB}/thop/libth_common.so /opt/trtllm_lib &&     cp ${TRTLLM_BUILD_LIB}/plugins/libnvinfer_plugin_tensorrt_llm.so         /opt/trtllm_lib &&     cp ${TRTLLM_BUILD_LIB}/plugins/libnvinfer_plugin_tensorrt_llm.so.9         /opt/trtllm_lib &&     cp ${TRTLLM_BUILD_LIB}/plugins/libnvinfer_plugin_tensorrt_llm.so.9.1.0         /opt/trtllm_lib

相关推荐

  1. 利用python构建Dockerfile 文件

    2024-04-11 13:16:05       35 阅读
  2. Dockerfile构建Python-Ubuntu-Opencv环境

    2024-04-11 13:16:05       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-11 13:16:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-11 13:16:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-11 13:16:05       87 阅读
  4. Python语言-面向对象

    2024-04-11 13:16:05       96 阅读

热门阅读

  1. Docker- Redis

    2024-04-11 13:16:05       48 阅读
  2. 视觉循迹小车(旭日x3派、opencv)

    2024-04-11 13:16:05       39 阅读
  3. uniApp使用textarea,默认高度且文字多后自适应设置

    2024-04-11 13:16:05       37 阅读
  4. flex布局的学习笔记

    2024-04-11 13:16:05       33 阅读
  5. web按钮点击打开qt窗体

    2024-04-11 13:16:05       36 阅读
  6. 自定义OPPO-r9s的kernel内核,并开启安卓支持docker

    2024-04-11 13:16:05       83 阅读
  7. R语言处理RNA等位基因不平衡(二)

    2024-04-11 13:16:05       41 阅读
  8. Ubuntu18.04安装Node.js教程

    2024-04-11 13:16:05       35 阅读
  9. R-tree总结

    2024-04-11 13:16:05       36 阅读
  10. 决策数分类算法代码

    2024-04-11 13:16:05       37 阅读
  11. 使用递归,手写实现数组的 flat 方法,两种方法

    2024-04-11 13:16:05       35 阅读
  12. gerrit 拉取失败

    2024-04-11 13:16:05       32 阅读