Movatterモバイル変換


[0]ホーム

URL:


Deploy Python Lambda functions with container images - AWS Lambda
DocumentationAWS LambdaDeveloper Guide
AWS base images for PythonUsing an AWS base imageUsing a non-AWS base image

Deploy Python Lambda functions with container images

There are three ways to build a container image for a Python Lambda function:

This page explains how to build, test, and deploy container images for Lambda.

AWS base images for Python

AWS provides the following base images for Python:

TagsRuntimeOperating systemDockerfileDeprecation

3.13

Python 3.13Amazon Linux 2023Dockerfile for Python 3.13 on GitHub

Jun 30, 2029

3.12

Python 3.12Amazon Linux 2023Dockerfile for Python 3.12 on GitHub

Oct 31, 2028

3.11

Python 3.11Amazon Linux 2Dockerfile for Python 3.11 on GitHub

Jun 30, 2026

3.10

Python 3.10Amazon Linux 2Dockerfile for Python 3.10 on GitHub

Jun 30, 2026

3.9

Python 3.9Amazon Linux 2Dockerfile for Python 3.9 on GitHub

Dec 15, 2025

Amazon ECR repository:gallery.ecr.aws/lambda/python

Python 3.12 and later base images are based on theAmazon Linux 2023 minimal container image. The Python 3.8-3.11 base images are based on the Amazon Linux 2 image. AL2023-based images provide several advantages over Amazon Linux 2, including a smaller deployment footprint and updated versions of libraries such asglibc.

AL2023-based images usemicrodnf (symlinked asdnf) as the package manager instead ofyum, which is the default package manager in Amazon Linux 2.microdnf is a standalone implementation ofdnf. For a list of packages that are included in AL2023-based images, refer to theMinimal Container columns inComparing packages installed on Amazon Linux 2023 Container Images. For more information about the differences between AL2023 and Amazon Linux 2, seeIntroducing the Amazon Linux 2023 runtime for AWS Lambda on the AWS Compute Blog.

Dependency search path in the base images

When you use animport statement in your code, the Python runtime searches the directories in its search path until it finds the module or package. By default, the runtime searches the{LAMBDA_TASK_ROOT} directory first. If you include a version of a runtime-included library in your image, your version will take precedence over the version that's included in the runtime.

Other steps in the search path depend on which version of the Lambda base image for Python you're using:

You can see the full search path for your Lambda function by adding the following code snippet.

import sys search_path = sys.pathprint(search_path)

Using an AWS base image for Python

To complete the steps in this section, you must have the following:

To create a container image from an AWS base image for Python
  1. Create a directory for the project, and then switch to that directory.

    mkdir examplecd example
  2. Create a new file calledlambda_function.py. You can add the following sample function code to the file for testing, or use your own.

  3. Create a new file calledrequirements.txt. If you're using the sample function code from the previous step, you can leave the file empty because there are no dependencies. Otherwise, list each required library. For example, here's what yourrequirements.txt should look like if your function uses the AWS SDK for Python (Boto3):

  4. Create a new Dockerfile with the following configuration:

    Note that the example Dockerfile does not include aUSER instruction. When you deploy a container image to Lambda, Lambda automatically defines a default Linux user with least-privileged permissions. This is different from standard Docker behavior which defaults to theroot user when noUSER instruction is provided.

  5. Build the Docker image with thedocker build command. The following example names the imagedocker-image and gives it thetesttag. To make your image compatible with Lambda, you must use the--provenance=false option.

    docker buildx build --platform linux/amd64 --provenance=false -tdocker-image:test .
  1. Start the Docker image with thedocker run command. In this example,docker-image is the image name andtest is the tag.

    docker run --platform linux/amd64 -p 9000:8080docker-image:test

    This command runs the image as a container and creates a local endpoint atlocalhost:9000/2015-03-31/functions/function/invocations.

  2. From a new terminal window, post an event to the local endpoint.

    Linux/macOS

    In Linux and macOS, run the followingcurl command:

    curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'

    This command invokes the function with an empty event and returns a response. If you're using your own function code rather than the sample function code, you might want to invoke the function with a JSON payload. Example:

    curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"payload":"hello world!"}'
    PowerShell

    In PowerShell, run the followingInvoke-WebRequest command:

    Invoke-WebRequest -Uri "http://localhost:9000/2015-03-31/functions/function/invocations" -Method Post -Body '{}' -ContentType "application/json"

    This command invokes the function with an empty event and returns a response. If you're using your own function code rather than the sample function code, you might want to invoke the function with a JSON payload. Example:

    Invoke-WebRequest -Uri "http://localhost:9000/2015-03-31/functions/function/invocations" -Method Post -Body '{"payload":"hello world!"}' -ContentType "application/json"
  3. Get the container ID.

    docker ps
  4. Use thedocker kill command to stop the container. In this command, replace3766c4ab331c with the container ID from the previous step.

    docker kill3766c4ab331c
To upload the image to Amazon ECR and create the Lambda function
  1. Run theget-login-password command to authenticate the Docker CLI to your Amazon ECR registry.

    • Set the--region value to the AWS Region where you want to create the Amazon ECR repository.

    • Replace111122223333 with your AWS account ID.

    aws ecr get-login-password --regionus-east-1 | docker login --username AWS --password-stdin111122223333.dkr.ecr.us-east-1.amazonaws.com
  2. Create a repository in Amazon ECR using thecreate-repository command.

    aws ecr create-repository --repository-namehello-world --regionus-east-1 --image-scanning-configuration scanOnPush=true --image-tag-mutability MUTABLE

    If successful, you see a response like this:

    { "repository":{ "repositoryArn": "arn:aws:ecr:us-east-1:111122223333:repository/hello-world", "registryId": "111122223333", "repositoryName": "hello-world", "repositoryUri": "111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world", "createdAt": "2023-03-09T10:39:01+00:00", "imageTagMutability": "MUTABLE", "imageScanningConfiguration":{ "scanOnPush": true }, "encryptionConfiguration":{ "encryptionType": "AES256" } }}
  3. Copy therepositoryUri from the output in the previous step.

  4. Run thedocker tag command to tag your local image into your Amazon ECR repository as the latest version. In this command:

    • docker-image:test is the name andtag of your Docker image. This is the image name and tag that you specified in thedocker build command.

    • Replace<ECRrepositoryUri> with therepositoryUri that you copied. Make sure to include:latest at the end of the URI.

    docker tag docker-image:test<ECRrepositoryUri>:latest

    Example:

    docker tagdocker-image:test111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
  5. Run thedocker push command to deploy your local image to the Amazon ECR repository. Make sure to include:latest at the end of the repository URI.

    docker push111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
  6. Create an execution role for the function, if you don't already have one. You need the Amazon Resource Name (ARN) of the role in the next step.

  7. Create the Lambda function. ForImageUri, specify the repository URI from earlier. Make sure to include:latest at the end of the URI.

    aws lambda create-function \ --function-namehello-world \ --package-type Image \ --code ImageUri=111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest \ --rolearn:aws:iam::111122223333:role/lambda-ex
  8. Invoke the function.

    aws lambda invoke --function-namehello-world response.json

    You should see a response like this:

    { "ExecutedVersion": "$LATEST", "StatusCode": 200}
  9. To see the output of the function, check theresponse.json file.

To update the function code, you must build the image again, upload the new image to the Amazon ECR repository, and then use theupdate-function-code command to deploy the image to the Lambda function.

Lambda resolves the image tag to a specific image digest. This means that if you point the image tag that was used to deploy the function to a new image in Amazon ECR, Lambda doesn't automatically update the function to use the new image.

To deploy the new image to the same Lambda function, you must use theupdate-function-code command, even if the image tag in Amazon ECR remains the same. In the following example, the--publish option creates a new version of the function using the updated container image.

aws lambda update-function-code \ --function-namehello-world \ --image-uri111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest \ --publish

Using an alternative base image with the runtime interface client

If you use anOS-only base image or an alternative base image, you must include the runtime interface client in your image. The runtime interface client extends theRuntime API, which manages the interaction between Lambda and your function code.

Install the theruntime interface client for Python using the pip package manager:

pip install awslambdaric

You can also download thePython runtime interface client from GitHub.

The following example demonstrates how to build a container image for Python using a non-AWS base image. The example Dockerfile uses an official Python base image. The Dockerfile includes the runtime interface client for Python.

To complete the steps in this section, you must have the following:

To create a container image from a non-AWS base image
  1. Create a directory for the project, and then switch to that directory.

    mkdir examplecd example
  2. Create a new file calledlambda_function.py. You can add the following sample function code to the file for testing, or use your own.

  3. Create a new file calledrequirements.txt. If you're using the sample function code from the previous step, you can leave the file empty because there are no dependencies. Otherwise, list each required library. For example, here's what yourrequirements.txt should look like if your function uses the AWS SDK for Python (Boto3):

  4. Create a new Dockerfile. The following Dockerfile uses an official Python base image instead of anAWS base image. The Dockerfile includes theruntime interface client, which makes the image compatible with Lambda. The following example Dockerfile uses amulti-stage build.

    • Set theFROM property to the base image.

    • Set theENTRYPOINT to the module that you want the Docker container to run when it starts. In this case, the module is the runtime interface client.

    • Set theCMD to the Lambda function handler.

    Note that the example Dockerfile does not include aUSER instruction. When you deploy a container image to Lambda, Lambda automatically defines a default Linux user with least-privileged permissions. This is different from standard Docker behavior which defaults to theroot user when noUSER instruction is provided.

    Example Dockerfile
    # Define custom function directoryARG FUNCTION_DIR="/function"FROMpython:3.12 AS build-image# Include global arg in this stage of the buildARG FUNCTION_DIR# Copy function codeRUN mkdir -p ${FUNCTION_DIR}COPY . ${FUNCTION_DIR}# Install the function's dependenciesRUN pip install \ --target ${FUNCTION_DIR} \ awslambdaric# Use a slim version of the base Python image to reduce the final image sizeFROMpython:3.12-slim# Include global arg in this stage of the buildARG FUNCTION_DIR# Set working directory to function root directoryWORKDIR ${FUNCTION_DIR}# Copy in the built dependenciesCOPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR}# Set runtime interface client as default command for the container runtimeENTRYPOINT [ "/usr/local/bin/python", "-m", "awslambdaric" ]# Pass the name of the function handler as an argument to the runtimeCMD [ "lambda_function.handler" ]
  5. Build the Docker image with thedocker build command. The following example names the imagedocker-image and gives it thetesttag. To make your image compatible with Lambda, you must use the--provenance=false option.

    docker buildx build --platform linux/amd64 --provenance=false -tdocker-image:test .

Use theruntime interface emulator to locally test the image. You canbuild the emulator into your image or use the following procedure to install it on your local machine.

To install and run the runtime interface emulator on your local machine
  1. From your project directory, run the following command to download the runtime interface emulator (x86-64 architecture) from GitHub and install it on your local machine.

    Linux/macOS
    mkdir -p ~/.aws-lambda-rie && \ curl -Lo ~/.aws-lambda-rie/aws-lambda-rie https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie && \ chmod +x ~/.aws-lambda-rie/aws-lambda-rie

    To install the arm64 emulator, replace the GitHub repository URL in the previous command with the following:

    https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie-arm64
    PowerShell
    $dirPath = "$HOME\.aws-lambda-rie"if (-not (Test-Path $dirPath)){ New-Item -Path $dirPath -ItemType Directory} $downloadLink = "https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie"$destinationPath = "$HOME\.aws-lambda-rie\aws-lambda-rie"Invoke-WebRequest -Uri $downloadLink -OutFile $destinationPath

    To install the arm64 emulator, replace the$downloadLink with the following:

    https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie-arm64
  2. Start the Docker image with thedocker run command. Note the following:

    Linux/macOS
    docker run --platform linux/amd64 -d -v ~/.aws-lambda-rie:/aws-lambda -p 9000:8080 \ --entrypoint /aws-lambda/aws-lambda-rie \docker-image:test \/usr/local/bin/python -m awslambdaric lambda_function.handler
    PowerShell
    docker run --platform linux/amd64 -d -v "$HOME\.aws-lambda-rie:/aws-lambda" -p 9000:8080 `--entrypoint /aws-lambda/aws-lambda-rie `docker-image:test `/usr/local/bin/python -m awslambdaric lambda_function.handler

    This command runs the image as a container and creates a local endpoint atlocalhost:9000/2015-03-31/functions/function/invocations.

  3. Post an event to the local endpoint.

    Linux/macOS

    In Linux and macOS, run the followingcurl command:

    curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'

    This command invokes the function with an empty event and returns a response. If you're using your own function code rather than the sample function code, you might want to invoke the function with a JSON payload. Example:

    curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"payload":"hello world!"}'
    PowerShell

    In PowerShell, run the followingInvoke-WebRequest command:

    Invoke-WebRequest -Uri "http://localhost:9000/2015-03-31/functions/function/invocations" -Method Post -Body '{}' -ContentType "application/json"

    This command invokes the function with an empty event and returns a response. If you're using your own function code rather than the sample function code, you might want to invoke the function with a JSON payload. Example:

    Invoke-WebRequest -Uri "http://localhost:9000/2015-03-31/functions/function/invocations" -Method Post -Body '{"payload":"hello world!"}' -ContentType "application/json"
  4. Get the container ID.

    docker ps
  5. Use thedocker kill command to stop the container. In this command, replace3766c4ab331c with the container ID from the previous step.

    docker kill3766c4ab331c
To upload the image to Amazon ECR and create the Lambda function
  1. Run theget-login-password command to authenticate the Docker CLI to your Amazon ECR registry.

    • Set the--region value to the AWS Region where you want to create the Amazon ECR repository.

    • Replace111122223333 with your AWS account ID.

    aws ecr get-login-password --regionus-east-1 | docker login --username AWS --password-stdin111122223333.dkr.ecr.us-east-1.amazonaws.com
  2. Create a repository in Amazon ECR using thecreate-repository command.

    aws ecr create-repository --repository-namehello-world --regionus-east-1 --image-scanning-configuration scanOnPush=true --image-tag-mutability MUTABLE

    If successful, you see a response like this:

    { "repository":{ "repositoryArn": "arn:aws:ecr:us-east-1:111122223333:repository/hello-world", "registryId": "111122223333", "repositoryName": "hello-world", "repositoryUri": "111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world", "createdAt": "2023-03-09T10:39:01+00:00", "imageTagMutability": "MUTABLE", "imageScanningConfiguration":{ "scanOnPush": true }, "encryptionConfiguration":{ "encryptionType": "AES256" } }}
  3. Copy therepositoryUri from the output in the previous step.

  4. Run thedocker tag command to tag your local image into your Amazon ECR repository as the latest version. In this command:

    • docker-image:test is the name andtag of your Docker image. This is the image name and tag that you specified in thedocker build command.

    • Replace<ECRrepositoryUri> with therepositoryUri that you copied. Make sure to include:latest at the end of the URI.

    docker tag docker-image:test<ECRrepositoryUri>:latest

    Example:

    docker tagdocker-image:test111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
  5. Run thedocker push command to deploy your local image to the Amazon ECR repository. Make sure to include:latest at the end of the repository URI.

    docker push111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
  6. Create an execution role for the function, if you don't already have one. You need the Amazon Resource Name (ARN) of the role in the next step.

  7. Create the Lambda function. ForImageUri, specify the repository URI from earlier. Make sure to include:latest at the end of the URI.

    aws lambda create-function \ --function-namehello-world \ --package-type Image \ --code ImageUri=111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest \ --rolearn:aws:iam::111122223333:role/lambda-ex
  8. Invoke the function.

    aws lambda invoke --function-namehello-world response.json

    You should see a response like this:

    { "ExecutedVersion": "$LATEST", "StatusCode": 200}
  9. To see the output of the function, check theresponse.json file.

To update the function code, you must build the image again, upload the new image to the Amazon ECR repository, and then use theupdate-function-code command to deploy the image to the Lambda function.

Lambda resolves the image tag to a specific image digest. This means that if you point the image tag that was used to deploy the function to a new image in Amazon ECR, Lambda doesn't automatically update the function to use the new image.

To deploy the new image to the same Lambda function, you must use theupdate-function-code command, even if the image tag in Amazon ECR remains the same. In the following example, the--publish option creates a new version of the function using the updated container image.

aws lambda update-function-code \ --function-namehello-world \ --image-uri111122223333.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest \ --publish

For an example of how to create a Python image from an Alpine base image, seeContainer image support for Lambda on the AWS Blog.

Deploy .zip file archives
Layers

[8]
ページ先頭

©2009-2025 Movatter.jp