I am trying to host a very simple (Hello World) FastAPI on AWS Lambda using Docker image. The image is working fine locally but when I am running it on Lambda it shows me the port binding error. Below are the error details that I am getting when I am trying to test the Lambda function with this image.
START RequestId: ae27e3b1-596d-41f3-a153-51cb9facc7a7 Version: $LATEST
INFO: Started server process [8]
INFO: Waiting for application startup.
INFO: Application startup complete.
ERROR: [Errno 13] error while attempting to bind on address ('0.0.0.0', 80): permission denied
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
END RequestId: ae27e3b1-596d-41f3-a153-51cb9facc7a7
REPORT RequestId: ae27e3b1-596d-41f3-a153-51cb9facc7a7 Duration: 3034.14 ms Billed Duration: 3000 ms Memory Size: 128 MB Max Memory Used: 20 MB
2021-11-01T00:23:59.807Z ae27e3b1-596d-41f3-a153-51cb9facc7a7 Task timed out after 3.03 seconds
This says that I cant bind port 80 on 0.0.0.0, so any idea what port and host should I use in the Dockerfile to make it work on AWS Lambda? Thanks (Below is the Dockerfile which I am using)
FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install -r /code/requirements.txt
COPY . /code
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
When running FastAPI in AWS Lambda (assuming used with AWS API Gateway , which you need for Lambda to receive HTTP requests) you can't run it using uvicorn and bind to a port as you would normally.
Instead you need to use Mangum which will create the Lambda handler and transform any incoming Lambda event and send it to FastAPI as a Request object, and in my experience it all works pretty well.
So your code to create the handler might look like this:
if __name__ == "__main__":
uvicorn.run("myapp:app")
else:
handler = Mangum(app)
Additionally your Dockerfile would have an entry point something like this:
ENTRYPOINT [ "/usr/local/bin/python", "-m", "awslambdaric" ]
CMD [ "myapp.handler" ]
Where awslambdaric is the python module provided by AWS to run Docker containers in AWS Lambda as describedhere .
Also note that API Gateway resource needs a method configured using the Lambda Proxy Integration.
I haven't tested any of the above its just an idea of how to get going.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.