Search code examples
pythonamazon-web-servicesdockeraws-lambda

Unable to Replicate AWS Lambda Guide for Python and Docker. Missing Module Error


I am trying to trouble shoot the error Traceback (most recent call last):andler 'handler' missing on module 'lambda_function' My understanding is that the CMD command I have in the Dockerfile can't find the function. However, I believe I followed the guide correctly.

Part of me thinks I am missing something outside of the guide that is needed. I am using WSL on Windows to run docker build, docker run, and for the curl request to test it all. Any recommendations on how to troubleshoot this?

Directory:

── project
├── lambda_function.py
├── Dockerfile
├── requirements.txt

Python code:

import sys
def handler(event, context):
    return 'Hello from AWS Lambda using Python' + sys.version + '!'

Dockerfile:

FROM public.ecr.aws/lambda/python:3.11

# Copy requirements.txt
COPY requirements.txt ${LAMBDA_TASK_ROOT}

# Install the specified packages
RUN pip install -r requirements.txt

# Copy function code
COPY lambda_function.py ${LAMBDA_TASK_ROOT}

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "lambda_function.handler" ]

Commands to test

docker build --platform linux/amd64 -t docker-image:test .

docker run -p 9000:8080 docker-image:test

Then I open a new terminal with the same directory

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

Error for curl request:

{"errorMessage": "Handler 'handler' missing on module 'lambda_function'", "errorType": "Runtime.HandlerNotFound", "requestId": "f76bd6cb-e91e-4197-842c-d8ae0c077a65", "stackTrace": []}

START RequestId: 0598dfd5-bd4d-406f-8c9d-d61ef4dffee4 Version: $LATEST
28 Oct 2023 17:03:02,249 [INFO] (rapid) extensionsDisabledByLayer(/opt/disable-extensions-jwigqn8j) -> stat /opt/disable-extensions-jwigqn8j: no such file or directory
28 Oct 2023 17:03:02,249 [INFO] (rapid) Configuring and starting Operator Domain
28 Oct 2023 17:03:02,249 [INFO] (rapid) Starting runtime domain
28 Oct 2023 17:03:02,249 [WARNING] (rapid) Cannot list external agents error=open /opt/extensions: no such file or directory
28 Oct 2023 17:03:02,249 [INFO] (rapid) Starting runtime without AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN , Expected?: false
Traceback (most recent call last):andler 'handler' missing on module 'lambda_function'
END RequestId: f76bd6cb-e91e-4197-842c-d8ae0c077a65
REPORT RequestId: f76bd6cb-e91e-4197-842c-d8ae0c077a65  Init Duration: 0.08 ms  Duration: 59.60 ms      Billed Duration: 60 ms  Memory Size: 3008 MB    Max Memory Used: 3008 MB

Solution

  • The Python file lambda_function.py was not saved so it was using a blank lambda_function.py file and failed since it could not find the expected function inside