7

I'm trying to build a Docker container that runs Python code on AWS Lambda. The build works fine, but when I test my code, I get the following error:

{"errorMessage": "Unable to import module 'function': No module named 'utils'", "errorType": "Runtime.ImportModuleError", "stackTrace": []}

I basically have two python scripts in my folder, function.py and utils.py, and I import some functions from utils.py and use them in function.py.

Locally, it all works fine, but when I build the Container and test it with the following curl command, I get the above error. Test curl command:

curl --request POST \
  --url http://localhost:9000/2015-03-31/functions/function/invocations \
  --header 'Content-Type: application/json' \
  --data '{"Input": 4}'

Here's my dockerfile:

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

WORKDIR /

COPY . .

COPY function.py ${LAMBDA_TASK_ROOT}

COPY requirements.txt .

RUN  pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"

CMD [ "function.lambda_handler" ]

What I read in related Stackoverflow questions is to try importing the functions from utils.py in another way, I've tried changing from utils import * to from .utils import all, I changed the WORKDIR in my Dockerfile, and I put the utils file in a separate utils folder and tried importing this way: from utils.utils import *. I have also tried running the code in Python 3.8.

Here's my folder structure: Here's my folder structure

Does anyone know what I'm doing wrong?

5
  • What's ${LAMBDA_TASK_ROOT} ? Shouldn't you be copying utils.py there too? Commented Jul 4, 2022 at 19:02
  • The ${LAMBDA_TASK_ROOT} I got from the AWS tutorial here. I didn't try explicitly copying the utils.py before (I thought this would be included in COPY . .?), but I just tried it anyway and got the same error :/ Commented Jul 4, 2022 at 19:24
  • COPY . . would copy all files to the workdir directory, which is /, while you want to copy the file to ${LAMBDA_TASK_ROOT} Commented Jul 4, 2022 at 19:38
  • 1
    Can you show the imports in function.py in the question? Commented Jul 4, 2022 at 19:39
  • Got it, thank you! Getting new errors now, so at least that one seems to be solved :) Commented Jul 4, 2022 at 19:47

1 Answer 1

2

The Dockerfile statement COPY . . copies all files to the working directory, which given your previous WORKDIR, is /.

To resolve the Python import issue, you need to move the Python module to the right directory:

COPY utils.py ${LAMBDA_TASK_ROOT}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.