2
1

More than 1 year has passed since last update.

Docker マルチステージビルドについて

Posted at

DockerでPython環境作成する際に以下のようなFROMが複数出てくるDockerfileがあった。

FROMが複数ってどういうこと?ってことで調べますと、
dockerのイメージ作成を段階的に実施できるとのこと。
何がうれしいかというとビルド環境をそのままデプロイするといらないものが入ってたりする(コンパイラとか)ので、実際にデプロイする環境は実行モジュールだけにしたいという思惑の模様。

# Define global args
ARG FUNCTION_DIR="/home/app/"
ARG RUNTIME_VERSION="3.9"
ARG DISTRO_VERSION="3.12"

# Stage 1 - bundle base image + runtime
# Grab a fresh copy of the image and install GCC
FROM python:${RUNTIME_VERSION}-alpine${DISTRO_VERSION} AS python-alpine
# Install GCC (Alpine uses musl but we compile and link dependencies with GCC)
RUN apk add --no-cache \
    libstdc++

# Stage 2 - build function and dependencies
FROM python-alpine AS build-image
# Install aws-lambda-cpp build dependencies
RUN apk add --no-cache \
    build-base \
    libtool \
    autoconf \
    automake \
    libexecinfo-dev \
    make \
    cmake \
    libcurl
# Include global args in this stage of the build
ARG FUNCTION_DIR
ARG RUNTIME_VERSION
# Create function directory
RUN mkdir -p ${FUNCTION_DIR}
# Copy handler function
COPY app/* ${FUNCTION_DIR}
# Optional – Install the function's dependencies
# RUN python${RUNTIME_VERSION} -m pip install -r requirements.txt --target ${FUNCTION_DIR}
# Install Lambda Runtime Interface Client for Python
RUN python${RUNTIME_VERSION} -m pip install awslambdaric --target ${FUNCTION_DIR}

# Stage 3 - final runtime image
# Grab a fresh copy of the Python image
FROM python-alpine
# 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 built dependencies
COPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR}
# (Optional) Add Lambda Runtime Interface Emulator and use a script in the ENTRYPOINT for simpler local runs
ADD https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie /usr/bin/aws-lambda-rie
COPY entry.sh /
RUN chmod 755 /usr/bin/aws-lambda-rie /entry.sh
ENTRYPOINT [ "/entry.sh" ]
CMD [ "app.handler" ]

●各ステージについて
ステージ 1では、ランタイム (この場合は Python 3.9)と、ステージ 2 で依存関係をコンパイルおよびリンクするために使用するGCCを使用してベース イメージをビルドします。
ステージ 2では、Lambda ランタイム インターフェイス クライアントをインストールし、関数と依存関係を構築します。
ステージ 3は、ステージ 2 からの出力をステージ 1 で構築されたベース イメージに追加する最終イメージを作成しています。ここでは、Lambda ランタイム インターフェイス エミュレーターも追加していますが、これはオプションです。

※Lambdaランタイムインターフェースエミュレーターを追加しない場合は以下を参照
https://aws.amazon.com/jp/blogs/aws/new-for-aws-lambda-container-image-support/

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1