在Docker中高效安装mariaDB客户端

20jt8wwn  于 5个月前  发布在  Docker
关注(0)|答案(2)|浏览(44)

我的Python应用程序需要以下包-> https://pypi.org/project/mysqlclient/
对我来说,这里的痛苦是安装这些包需要在我的Dockerfile中进行以下构建阶段:

RUN curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | sudo bash && \
    apt-get update && \
    apt-get install -y mariadb-client libmariadb-dev-compat libmariadb-dev

字符串
为了让这个RUN命令正常工作,你还需要安装gcc和pkg-config,否则mariadb-client在安装过程中无法编译。这种安装方式在docker中有点难看,因为它会因为安装gcc而大量放大镜像大小。
我怎样才能在不安装gcc的情况下安装这些软件包?这里有没有可以使用的预编译的二进制文件?
先谢了。

6ioyuze2

6ioyuze21#

使用a multi-stage build在第一阶段构建mysqlclient wheel,然后将其复制到运行时阶段。这使得gcc和朋友仅处于构建阶段。
当然,您也可以为所有requirements.txtpip wheel -w /deps -r requirements.txt或诸如此类的东西)执行此操作。

FROM python:3.12 as mysqlclient-build
RUN curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | bash 
RUN apt-get update
RUN apt-get install -y mariadb-client libmariadb-dev-compat libmariadb-dev
RUN pip wheel -w /deps mysqlclient

FROM python:3.12
COPY --from=mysqlclient-build /deps/*.whl /deps
RUN pip install /deps/*.whl && rm -rf /deps
# ... the rest of your actual application bits

字符串
根据mysqlclient轮是否静态链接运行时libmariadb库,您可能需要也可能不需要在运行时阶段也apt-get install

deikduxw

deikduxw2#

这也是我的最终解决方案:
1.构建mysqlclient轮

FROM python:3.11.7-slim-bookworm as mariadb_client_builder
    
    # Install build dependencies
    RUN apt-get update && \
        apt-get install -y gcc pkg-config curl
    
    RUN curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | bash && \
        apt-get update && \
        apt-get install -y libmariadb-dev
    
    # Install mysqlclient, building it into a wheel file
    RUN pip wheel --no-cache-dir --wheel-dir=/usr/src/app/wheels mysqlclient

字符串
1.在最终图像中使用滚轮:

COPY --from=mariadb_client_builder /usr/src/app/wheels /wheels

    # Setup virtualenv
    RUN pip install --upgrade pip && \
        pip install setuptools virtualenv && \
        python -m virtualenv /venv && \
        . /venv/bin/activate && \
        pip install --no-cache /wheels/* && \
        pip install -r requirements.txt && \
        deactivate


确保mysqlclient不再是requirements.txt的一部分,因为我们直接从预编译的wheel安装到venv中。
注意,Pypi mysqlclient还需要在最终映像中安装libmariadb-dev包,因此您绝对需要在最终映像中执行以下操作:

RUN curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | bash && \
        apt-get update && \
        apt-get install -y libmariadb-dev


你基本上需要libmariadb-dev包来构建wheel,然后将最终镜像连接到mariadb/mysql示例。

相关问题