SAM Lambda python function not connecting to local dynamoDb in docker

Viewed 624

I have installed dynamodb in a docker container and from the command line I am able to write and read records from it. However, when I try to connect to the database using Python3 I get an error.

Could not connect to the endpoint URL: "http://localhost:8000/": EndpointConnectionError

This is my code snippet

import os
import uuid
import json
import boto3
import traceback
from botocore.exceptions import ClientError

print('Loading function')

region_name = os.environ["REGION_NAME"]
dynamo = boto3.client("dynamodb")
table_name = os.environ["TABLE_NAME"]
musicAlbum_table = boto3.resource("dynamodb", endpoint_url="http://localhost:8000/").Table(table_name)

def respond(err, res=None):
    return {
        'statusCode': '400' if err else '200',
        'body': err.message if err else json.dumps(res),
        'headers': {
            'Content-Type': 'application/json',
        },
    }


def lambda_handler(event, context):

    print("table_name="+ table_name)
    musicAlbum_table.put_item(
                Item={
                    'Artist': 'Joe Satriani',
                    'SongTitle': 'Circles',
                    'AlbumTitle': 'Surfing with an Alien'
                  }
            )
    scan_result = dynamo.scan(TableName=table_name)
    return respond(None, res=scan_result)
1 Answers

On Mac and Windows with a recent version of Docker, use the hostname 'host.docker.internal' with the http protocol (non-secure) in the boto resource creation. Then, the local lambda running in a container will have network access to the local dynamodb running on the host.

musicAlbum_table =
   boto3.resource("dynamodb",
               endpoint_url="http://host.docker.internal:8000/")
               .Table(table_name)

On Linux it's less easy, maybe wait till v20.04 and wait for the cli command '--add-host host.docker.internal:host-gateway'. I just throw my hands up on Linux.

Related