user1584120
user1584120

Reputation: 1261

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

Upvotes: 6

Views: 6749

Answers (4)

David Lavieri
David Lavieri

Reputation: 1070

For anyone that may wander here how to achieve a connection with dynamodb and lambda, both running in a docker container. Started as a comment but wanted to provide examples.

  • Option 1: use docker compose with both containers as services in docker-compose.yaml file

  • Option 2: with standalone containers, manually create a local docker bridge network and connect both containers to it, here the steps to reproduce:

Create the network

sudo docker network create -d bridge [dynamodb_net]

Start the dynamo container, give it a name so your lambda will be able to to find it

sudo docker run --rm -it --network dynamodb_net -p 8000:8000 --name [dynamo-local] [dynamo-image]

Start your lambda container in the same fashion, you can add name to this container if you want to

sudo docker run --rm -it --network dynamodb_net -p 9000:8080 [lambda-image]

NOTE: the items in [here] can be changed if you need to

EDIT: added ports flag

Upvotes: 0

Stefan
Stefan

Reputation: 101

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.

Upvotes: 10

Massimo Selvi
Massimo Selvi

Reputation: 21

you can run DynamoDB locally inside a container, but I wonder how to call it from the SAM's Lambda container (local as well)

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

Upvotes: 0

ptomli
ptomli

Reputation: 11818

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.

Upvotes: 8

Related Questions