15
3

More than 1 year has passed since last update.

Dockerを使用してAWS lambdaのPython3.9.6実行環境を構築し、pandasのLayerを作成する

Posted at

はじめに

AWS LambdaのPython3.9ランタイムで使用するpandasのモジュールをローカルで作成してもうまくいかなかったので、DockerでLambda実行環境を再現し、pandasのLayerを作成した。
今回の記事を作成するにあたり、こちらのQiita記事を参考にさせて頂きました。

実行環境

  • Windows 10 Pro

  • Git Bash

Dockerイメージの作成

Dockerfile

FROM amazonlinux:2

ARG PYTHON_VERSION=3.9.6

RUN yum update -y && yum install -y tar gzip make gcc openssl-devel bzip2-devel libffi-devel \
  && curl https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz | tar xz \
  && cd Python-${PYTHON_VERSION} && ./configure && make && make install \
  && cd - && rm -rf Python-${PYTHON_VERSION}

RUN yum install -y zip \
  && mkdir /python \
  && mkdir /dist

ENTRYPOINT ["/bin/bash"]

こちらより、Python3.9ランタイムはAmazon Linux 2で動いているため、該当するDocker Hubの公式イメージを活用した。
Pythonのバージョンはこちらにあるものは指定可能。
pandasなどのモジュールをインストールするpythonディレクトリと、zipファイルを置くdistディレクトリを作成した。
Dockerコンテナ内でコマンドを実行するため、ENTRYPOINTを"/bin/bash"とした。

Dockerイメージのビルド

$ docker build . -t lambda-layer:python3.9

イメージ名は何でも良いが、ここではlambda-layer:python3.9とした。

イメージからコンテナを生成し、コンテナ内に潜り込む

$ winpty docker container run -it --name "test" lambda-layer:python3.9

ここでは、--nameオプションでコンテナ名を"test"とした。
また、Git Bushを用いてWindowsでbashを利用し、Dockerコンテナ内に入ろうとすると以下のようなエラーが出るので、先頭にwinptyを付けて実行した(詳しくはこちらを参照)。

the input device is not a TTY.  If you are using mintty, try prefixing the command with 'winpty'

コンテナ内でpandasをインストールする

# pip3 install -t /python pandas

コンテナ内で、pandasをpip3でインストールした。-tオプションでモジュールのインストール先をpythonディレクトリに指定した。
このときpandasと依存関係にあるnumpyやpytzなども一緒にインストールされた。

pythonディレクトリ内のモジュールをzipで固める

# zip -r /dist/pandas.zip /python

固めたものをpandas.zipとし、distディレクトリに置いた。

作成したzipファイルをローカルにコピーする

$ docker cp [CONTAINER ID]:/dist/pandas.zip ./

lambdaにアップロードするために、作成したzipファイルをローカル環境にコピーした。
CONTAINER IDは以下のコマンドで確認できる。

$ docker container ls -a
15
3
1

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
15
3