connecting AWS SAM Local with dynamodb in docker

Many thanks to Heitor Lessa who answered me on Twitter with an example repo

Which pointed me at the answer…

  • dynamodb’s docker container is on 127.0.0.1 from the context of my
    machine (which is why I could interact with it)

  • SAM local’s docker container is on 127.0.0.1 from the context of my
    machine

  • But they aren’t on 127.0.0.1 from each other’s context

So: https://github.com/heitorlessa/sam-local-python-hot-reloading/blob/master/users/users.py#L14

Pointed me at changing my connection code to:

const AWS = require('aws-sdk')
const awsRegion = process.env.AWS_REGION || 'eu-west-2'

let dynamoDbClient
const makeClient = () => {
  const options = {
    region: awsRegion
  }
  if(process.env.AWS_SAM_LOCAL) {
    options.endpoint="http://dynamodb:8000"
  }
  dynamoDbClient = new AWS.DynamoDB.DocumentClient(options)
  return dynamoDbClient
}

module.exports = {
  connect: () => dynamoDbClient || makeClient()
}

with the important lines being:

if(process.env.AWS_SAM_LOCAL) {
  options.endpoint="http://dynamodb:8000"
}

from the context of the SAM local docker container the dynamodb container is exposed via its name

My two startup commands ended up as:

docker run -d -v "$PWD":/dynamodb_local_db -p 8000:8000 --network lambda-local --name dynamodb cnadiminti/dynamodb-local

and

AWS_REGION=eu-west-2 sam local start-api --docker-network lambda-local

with the only change here being to give the dynamodb container a name

Leave a Comment