This document describes how to use docker-compose to start a container with DynamoDb locally, add a table and connect to it from .NET Core.
You can create the table by getting the table attributes using the describe-table operation
aws dynamodb describe-table --table-name some.table > table.json
Below is the service description for using DynamoDb with added comments. This refers to version 3.7 of the compose file.
dynamodb:
build:
context: ../Infrastructure/Docker/DynamoDB/ # Location of the Dockerfile
environment:
- HOSTNAME_EXTERNAL=dynamodb # Name of the host to expose the services externally
- SERVICES=dynamodb # List of AWS services to start, seperated by a comma ","
- AWS_DEFAULT_REGION=ap-southeast-2 # AWS region
- AWS_ACCESS_KEY_ID=foo # AWS Access Key - I use "foo" for all services
- AWS_SECRET_ACCESS_KEY=bar # AWS Secret Key - I use "bar" for all services
ports:
- "4569:4569" # Number of port to expose externally
Below are the commands used to create the container with added comments.
# Image to use. I found version 0.9.6 to be very stable
FROM localstack/localstack:0.9.6
# Number of port to expose externally
EXPOSE 4569
# Copy in table creation scripts. The directory below should be in the same directory as the Dockerfile
COPY ./docker-entrypoint-initaws.d /docker-entrypoint-initaws.d
Localstack will attempt to run all files in the docker-entrypoint-initaws.d directory*
Create a shell file with the following contents:
aws --endpoint-url http://dynamodb:4569 --region ap-southeast-2 \
dynamodb create-table --cli-input-json file:///docker-entrypoint-initaws.d/table.json
* Make sure your files are saved with line feeds. Add the following to your .gitattributes
*.sh text eol=lf
There are currently 2 options to create a local instance of DynamoDb
- localstack
https://github.com/localstack/localstack - DynamoDB Local
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html
I choose to go with localstack as it uses the same creation mechanism for every AWS component i.e. you just copy scripts into the docker-entrypoint-initaws.d directory and localstack will process them.
You can now start DynamoDb using:
docker-compose --file docker-compose.yml up --build
By default all amazon clients try to connect to AWS in the cloud. You will need to pass in a service URL to configure the client to use the container.
services.AddSingleton<IAmazonDynamoDB>(client =>
{
if (string.IsNullOrEmpty(awsConfig.DynamoDbServiceUrl))
{
return new AmazonDynamoDBClient(credentials, region);
}
// Localstack support
var config = new AmazonDynamoDBConfig
{
ServiceURL = awsConfig.DynamoDbServiceUrl
};
// Dynamo won't work with empty credentials
return new AmazonDynamoDBClient(new BasicAWSCredentials("foo", "bar"), config);
});