【问题标题】:Error calling Flask endpoint in AWS EC2 from AWS Lambda从 AWS Lambda 调用 AWS EC2 中的 Flask 端点时出错
【发布时间】:2020-09-19 01:04:08
【问题描述】:

总结

我有一个使用 gunicorn 启动的烧瓶服务器,它创建了一个我想从 AWS lambda 函数调用的端点。但是,当我在 Lambda 中运行测试时,它会返回

  "errorMessage": "HTTPConnectionPool(host='<ip_of_ec2>', port=8000): Max retries exceeded with url: /api/v1/my_project(Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7efec823ed60>: Failed to establish a new connection: [Errno 111] Connection refused'))",
  "errorType": "ConnectionError",
  "stackTrace": [
    "  File \"/var/lang/lib/python3.8/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\n",
...
    "  File \"/var/task/requests/adapters.py\", line 516, in send\n    raise ConnectionError(e, request=request)\n"
  ]
}

我需要在 AWS 中进行哪些配置才能允许此调用,或者我缺少什么以便 lambda 函数可以建立此连接。

我有什么

不用说一切都在本地运行(我可以运行 curl 来调用 EC2 上的端点并建立连接)。 Lambda 和 EC2 在同一个 vpc 上,以防安全组接受所有出站和入站流量。

Lambda 函数

import requests

print('Loading function')
url = 'http://<ip_of_ec2>:8000/api/v1/my_project'


def respond(err, res=None):

    return {
        'statusCode': '400' if err else res.status_code,
        'body': err.message if err else res.json(),
        'headers': {
            'Content-Type': 'application/json',
        },
    }

def call_project(claim, link):
    return requests.post(url=url, json={"claim": claim, "link": link})


def lambda_handler(event, context):

    operations = {
        'POST': lambda x: call_project(**x)
    }

    operation = event['httpMethod']
    if operation in operations:
        payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
        return respond(None, operations[operation](payload))
    else:
        return respond(ValueError('Unsupported method "{}"'.format(operation)))

Flask 端点

@app.route('/api/v1/my_project', methods=['GET', 'POST'])
def my_project():
    content = request.get_json()
  ...
    return jsonify(full_pre_json)

Gunicorn 配置

bind = "0.0.0.0:8000"
workers = 1

timeout = 3 * 60  # 3 minutes

【问题讨论】:

  • ip_of_ec2 是私有IP还是公共IP?
  • 我相信是公开的

标签: python flask amazon-ec2 aws-lambda gunicorn


【解决方案1】:

尝试将 AWS Lambda 配置为具有执行角色以与同一 VPC 中的 aws 资源进行交互。

执行角色: https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html

教程: https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html

【讨论】:

  • 感谢您的建议,很抱歉我花了这么长时间才实施它。不幸的是,这些链接似乎无助于解决问题。 lambda 具有 VPC 执行角色;并且 EC2 实例和 lambda 都在同一个 vpc 和安全组上。只是为了确认 lambda 的一切正常,我将 RDS 连接到同一个 lambda 并确认连接适用于此。
【解决方案2】:

解决方案很容易实施,但不幸的是很难发现。我遇到的错误可能是由于 VPC 的配置错误造成的,但在我的情况下,我只是输入了错误的 IP 地址。

我应该使用的 ip_of_ec2 是私有 IP 地址,而不是公共 IP。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2021-07-23
    相关资源
    最近更新 更多