LoginSignup
3
3

DockerでLambdaのPython(3.10)レイヤー作成してみた!

Posted at

psycopg2とかpillowとかを単にpip installするとLambdaでimport module errorが発生するので、それを解決するためにDockerでLambdaのランタイムを再現しつつ?レイヤーをzipで作成した。

0. 前提条件

  • Dockerコマンドが使える状態になっている
  • awsアカウントを作成済みになっている

1. Dockerイメージを作成する

Dockerfile
FROM --platform=linux/x86_64 amazonlinux:2

ARG PYTHON_VERSION=3.10.5

RUN yum update -y && yum install -y tar gzip make gcc epel-release openssl11 openssl11-devel bzip2-devel libffi-devel \
  && curl https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz | tar xz \
  && export CFLAGS=$(pkg-config --cflags openssl11) && export LDFLAGS=$(pkg-config --libs openssl11) \
  && cd Python-${PYTHON_VERSION} && ./configure && make && make install \
  && cd - && rm -rf Python-${PYTHON_VERSION}

ADD entrypoint.sh /

RUN yum install -y zip \
  && mkdir /python \
  && chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

m1 macとかだと--platform=linux/x86_64をしてしないと、勝手にlinux/amd64でインストールされてしまうので、一応指定しておく。(amd64でインストールしてしまうと、Lambdaでもamd64をしてしなくてはならないかも)
python3.10以降よりopenssl 1.1.1が必須になったため、epel-release,openssl11,openssl11-develもインストールしておく。
これをインストールしないと以下のエラーが出る。

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

2. シェルスクリプトを作成する

entrypoint.sh
#!/bin/bash -eu

SRC=/python
DIST=/dist/layer.zip

pip3 install -t ${SRC} $@
rm -f ${DIST}
zip -q -r ${DIST} ${SRC}

3. イメージをビルドする

docker build . -t bundle-pip-modules-for-aws-lambda-layers:python3.10

4. requirements.txtを作成する

requirements.txt
psycopg2-binary
pillow

Lambdaで使用したいライブラリを書いておく。

5. Lambdaのレイヤーを作成する

Mac, linuxの場合

docker run --rm \
    -v $(pwd)/requirements.txt:/requirements.txt \
    -v $(pwd):/dist \
    bundle-pip-modules-for-aws-lambda-layers:python3.10 \
    -r requirements.txt

windowsの場合

docker run --rm \
    -v {カレントディレクトリ}/requirements.txt:/requirements.txt \
    -v {カレントディレクトリ}:/dist \
    bundle-pip-modules-for-aws-lambda-layers:python3.10 \
        -r requirements.txt

正常に終わればlayer.zipが作成される。

6. レイヤーを登録する

スクリーンショット (44).png

あとは使用するLambdaにレイヤーを追加して、試してみるだけです!

参考文献

  1. Docker で AWS Lambda の Python 用 Layer を作成する
  2. pipコマンドでモジュールインストール時にSSLエラー時の対処方法
  3. Python 3.10の新機能(その8) OpenSSL 1.1.1が必須に
  4. M1 Mac で Docker の x86_64 向けイメージを使う
  5. AWS Lambdaで発生する psycopg2._psycopg の ImportModuleError を解決する方法
3
3
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
3
3