简体   繁体   中英

sam local start-api go lambda returns 502 "internal server error" on linux ubuntu


While running aws sam application locally returns "Internal server error".

I created aws sam hello-world example using:
curl 127.0.0.1:3000/hello

then I run app locally using:

Invoking hello-world (go1.x)<br>
Image was not found.<br>
Building image....................................<br>
Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-go1.x:rapid-1.15.0.<br>

Mounting /home/robert/projects/try_dir/try_sam_go_daemons/robertsamlocallyhelloworld/hello-world as /var/task:ro,delegated inside runtime container<br>
START RequestId: 159c8e80-649d-4c71-8b54-3221387af308 Version: $LATEST<br>
fork/exec /var/task/hello-world: no such file or directory: PathError<br>
null<br>
END RequestId: 159c8e80-649d-4c71-8b54-3221387af308<br>
REPORT RequestId: 159c8e80-649d-4c71-8b54-3221387af308  Init Duration: 0.38 ms  Duration: 9.30 ms   Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 128 MB <br>
Lambda returned empty body!<br>
Invalid lambda response received: Invalid API Gateway Response Keys: {'errorMessage', 'errorType'} in {'errorMessage': 'fork/exec /var/task/hello-world: no such file or directory', 'errorType': 'PathError'}<br>
2021-01-11 23:55:41 127.0.0.1 - - [11/Jan/2021 23:55:41] "GET /hello HTTP/1.1" 502 <br>
2021-01-11 23:55:41 127.0.0.1 - - [11/Jan/2021 23:55:41] "GET /favicon.ico HTTP/1.1" 403 <br>

then:

 curl 127.0.0.1:3000/hello

Image downloading has started and then stopped after a while.

/hello endpoint returns: 502 "Internal server error"

I am using:
Sam Cli: 1.15.0
Docker: 20.10.0

Output:

 Invoking hello-world (go1.x)<br> Image was not found.<br> Building image....................................<br> Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-go1.x:rapid-1.15.0.<br> Mounting /home/robert/projects/try_dir/try_sam_go_daemons/robertsamlocallyhelloworld/hello-world as /var/task:ro,delegated inside runtime container<br> START RequestId: 159c8e80-649d-4c71-8b54-3221387af308 Version: $LATEST<br> fork/exec /var/task/hello-world: no such file or directory: PathError<br> null<br> END RequestId: 159c8e80-649d-4c71-8b54-3221387af308<br> REPORT RequestId: 159c8e80-649d-4c71-8b54-3221387af308 Init Duration: 0.38 ms Duration: 9.30 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 128 MB <br> Lambda returned empty body:<br> Invalid lambda response received: Invalid API Gateway Response Keys, {'errorMessage': 'errorType'} in {'errorMessage': 'fork/exec /var/task/hello-world, no such file or directory': 'errorType': 'PathError'}<br> 2021-01-11 23:55.41 127.0.0:1 - - [11/Jan/2021 23:55.41] "GET /hello HTTP/1:1" 502 <br> 2021-01-11 23:55.41 127.0.0:1 - - [11/Jan/2021 23:55.41] "GET /favicon.ico HTTP/1.1" 403 <br>

The error message clearly states:

Invalid API Gateway Response Keys

I faced a similar error in which I received error for the response status_code:

Invalid lambda response received: Invalid API Gateway Response Keys: {'status_code'} in {'status_code': 200, 'body': '"Success!!"'}

Apparently, SAM tries to mock the API Gateway and status_code was not one of the keys API Gateway expects in the response. Therefor I changed it to key from status_code to statusCode

    return {
    'statusCode': 200,
    'body': json.dumps("Success!!")
}

And, it worked fine.

I would suggest you take a look at API Gateway response keys and try to map your response to that.

I also got this error because the local invocation doesn't have access to environment variables referenced in the template.yml. eg.:

...
 #template.yml
     Policies:
    # Give Create/Read/Update/Delete Permissions to the SampleTable
    - DynamoDBCrudPolicy:
        TableName: !Ref SampleTable
  Environment:
    Variables:
      # Make table name accessible as environment variable from function code during execution
      SAMPLE_TABLE: !Ref SampleTable

...

One solution is to deploy the app and fetch the env variables from the console, then input them into a "env.json" or similar:

{
"getAllItemsFunction": {
    "SAMPLE_TABLE": "dev-demo-SampleTable-*ID*"
},}

Then you can use the deployed table in your local development by adding -e env.json to the sam local invoke command . Like this: sam local invoke getAllItemsFunction -e events/event-get-all-items.json -n env.json

Honestly dont know where the connection between SAMPLE_TABLE and ",Ref SampleTable" is happening. but it works: Take a look at this: https://youtu.be/NzPqMrdgD1s?t=799

Same answer I wrote on https://stackoverflow.com/a/72067740/93074

So from the following tutorial covering how to get lambdas and api-gateway working using CDK , I managed to isolate that without the following line will result in the 502 BAD GATEWAY error experienced, with the suggested return type as described. It's in the new apigateway.RestApi props.

defaultCorsPreflightOptions: {
...
        allowOrigins: ['http://localhost:3000'],
      },

The op doesn't specify his infrastructure propositioning method. If not using the CDK and using Cloud Formation YAML then it's probably related to the equivalent in the expanded YAML (although the.net result of the expansion is beyond my competency).

method.response.header.Access-Control-Allow-Origin

BrokerAPItest41BB435C:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt 'BrokerAPID825C3CC.RootResourceId'
      PathPart: test
      RestApiId: !Ref 'BrokerAPID825C3CC'
    Metadata:
      aws:cdk:path: BrokerAwsDeployStack/BrokerAPI/Default/test/Resource
  BrokerAPItestOPTIONS843EE5C3:
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: OPTIONS
      ResourceId: !Ref 'BrokerAPItest41BB435C'
      RestApiId: !Ref 'BrokerAPID825C3CC'
      AuthorizationType: NONE
      Integration:
        IntegrationResponses:
          - ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: '''Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'''
              method.response.header.Access-Control-Allow-Origin: '''http://localhost:3000'''
              method.response.header.Vary: '''Origin'''
              method.response.header.Access-Control-Allow-Methods: '''OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'''
            StatusCode: '204'
        RequestTemplates:
          application/json: '{ statusCode: 200 }'
        Type: MOCK
      MethodResponses:
        - ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Origin: true
            method.response.header.Vary: true
            method.response.header.Access-Control-Allow-Methods: true
          StatusCode: '204'
    Metadata:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM