Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamoDb locally with lambda

I think this is possible? I have a lambda and api gateway defined in a sam template. I use sam-local to start that up. Within my lambda I would like to connect to my local dynamoDB but the lambda keeps timing out. Code looks like:

let AWS = require('aws-sdk')
let dyn= new AWS.DynamoDB({ endpoint: new AWS.Endpoint("http://localhost:8000") })

function handler(event, context, callback) {
  dyn.listTables({Limit: 10}, function(err, data) {
    if (err) {
      console.log("Error", err.code)
    } else {
      console.log("Table names are ", data.TableNames)
    }
  })

  let response = {
    statusCode: 200
  }
  callback(null, response)
}

If this code is run outside of a lambda it works fine

like image 902
user1584120 Avatar asked Jan 19 '18 14:01

user1584120


People also ask

Can you use DynamoDB locally?

DynamoDB Local is available as a download (requires JRE), as an Apache Maven dependency, or as a Docker image. If you prefer to use the Amazon DynamoDB web service instead, see Setting up DynamoDB (web service).

How do I access DynamoDB locally?

To access DynamoDB running locally, use the --endpoint-url parameter. The following is an example of using the AWS CLI to list the tables in DynamoDB on your computer. The AWS CLI can't use the downloadable version of DynamoDB as a default endpoint. Therefore, you must specify --endpoint-url with each AWS CLI command.


2 Answers

Your DynamoDB is running on the local machine, while the SAM Local is running inside a Docker container.

If you create a Docker container for DynamoDB to run in, and have this in the same Docker network as the SAM Local container, you might have more success.

like image 181
ptomli Avatar answered Oct 13 '22 20:10

ptomli


I'm doing the same thing as you. But I run locally my DynamoDB as a docker image using this command. I run this on mac:

docker run -p 8000:8000 amazon/dynamodb-local

In your code change this:

endpoint: new AWS.Endpoint("http://localhost:8000")

to this:

endpoint: new AWS.Endpoint("http://docker.for.mac.localhost:8000")

Now lambda can connect to port and will not timed out.

like image 22
Stefan Avatar answered Oct 13 '22 21:10

Stefan