Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Module Error when building a Docker Container with Python for AWS Lambda

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?

like image 510
tom Avatar asked Aug 13 '26 07:08

tom


1 Answers

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}
like image 82
Paolo Avatar answered Aug 15 '26 20:08

Paolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!