I am getting connection refused error while connecting to dynamodb (localstack) from lambda written in Typescript
I use localstack to emulate the AWS resource and below is how I am accessing the dynamodb
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
DynamoDBDocumentClient,
ScanCommand
} from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({
region: process.env.CDK_DEFAULT_REGION,
endpoint: 'http://localhost:4566',
});
const dynamo = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.TABLE_NAME || '';
export const handler = async (event: any) => {
try {
console.log('connecting to dyname db: ' + TABLE_NAME)
var body = await dynamo.send(
new ScanCommand({ TableName: TABLE_NAME })
);
const response = body?.Items;
return { statusCode: 200, body: JSON.stringify(response) };
} catch (dbError) {
console.log('Unable to get the data from dyname db: ' + TABLE_NAME)
return { statusCode: 500, body: JSON.stringify(dbError) };
}
};
and below is the error what I am getting.
{
"errno": -111,
"code": "ECONNREFUSED",
"syscall": "connect",
"address": "127.0.0.1",
"port": 4566,
"$metadata": {
"attempts": 3,
"totalRetryDelay": 32
}
}
where as I am able to get the details through AWS CLI command.
aws --endpoint-url=http://localhost:4566 dynamodb scan --table-name <table-name>
if your lambda code is running inside localstack
The LocalStack instance/resources is available at the domain localhost.localstack.cloud. All subdomains of localhost.localstack.cloud also resolve to the LocalStack instance.
I was able to connect to localstack dynamo after modifying the DynamoDBClient creation like below.
Localstack documentation : Accessing LocalStack via the endpoint URL