我正在創建一個運行 Python 3.6.15 的 Docker 容器,并且我的 Dockerfile 中的 pip install 函式在構建程序中運行,但是當我在構建完成后嘗試在其中執行函式并運行它時,“已安裝”包不存在.
有關更多背景關系,這是我的 Dockerfile。為清楚起見,我正在構建一個 Docker 容器,該容器正在上傳到 AWS ECR 以在 Lambda 函式中使用,但我認為這與這個問題并不完全相關(盡管有利于背景關系):
# Define function directory
ARG FUNCTION_DIR="/function"
FROM python:3.6 as build-image
# Install aws-lambda-cpp build dependencies
RUN apt-get clean && apt-get update && \
apt-get install -y \
g \
make \
cmake \
unzip \
libcurl4-openssl-dev \
ffmpeg
# Include global arg in this stage of the build
ARG FUNCTION_DIR
# Create function directory
RUN mkdir -p ${FUNCTION_DIR}
# Copy function code
COPY . ${FUNCTION_DIR}
# Install the runtime interface client
RUN /usr/local/bin/python -m pip install \
--target ${FUNCTION_DIR} \
awslambdaric
# Install the runtime interface client
COPY requirements.txt /requirements.txt
RUN /usr/local/bin/python -m pip install -r requirements.txt
# Multi-stage build: grab a fresh copy of the base image
FROM python:3.6
# Include global arg in this stage of the build
ARG FUNCTION_DIR
# Set working directory to function root directory
WORKDIR ${FUNCTION_DIR}
# Copy in the build image dependencies
COPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR}
COPY entry-point.sh /entry_script.sh
ADD aws-lambda-rie /usr/local/bin/aws-lambda-rie
ENTRYPOINT [ "/entry_script.sh" ]
CMD [ "app.handler" ]
當我docker run
在終端中運行命令時,我可以看到它正在從專案根目錄中的 requirements.txt 檔案中收集和安裝包。然后我嘗試運行獲取匯入模塊錯誤。為了排除故障,我運行了一些命令列exec
功能,例如:
docker exec <container-id> bash -c "ls" # This returns the folder structure which looks great
docker exec <container-id> bash -c "pip freeze". # This only returns 'pip', 'wheel' and some other basic Python modules
我能解決它的唯一原因是在我構建并運行它之后,我運行這個命令:
docker exec <container-id> bash -c "/usr/local/bin/python -m pip install -r requirements.txt"
它手動安裝模塊,然后它們出現在freeze
命令中,我可以執行代碼。這并不理想,因為我希望pip install
在構建程序中正確運行,因此將來我對代碼進行更改時步驟會更少。
任何關于我哪里出錯的指示都會很棒,謝謝!
uj5u.com熱心網友回復:
根據Docker Docs,多階段構建
對于多階段構建,您可以在 Dockerfile 中使用多個 FROM 陳述句。每個 FROM 指令都可以使用不同的基礎,并且它們中的每一個都開始構建的新階段。您可以選擇性地將工件從一個階段復制到另一個階段,從而在最終影像中留下您不想要的一切。
所以from python:3.6
Dockerfile 中的第二個重置了鏡像構建,洗掉了模塊安裝。
隨后的副本保存了/function
(aws 模塊)中的內容,但不保存其他 pip 安裝中保存到系統的其他模塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/468843.html