Reputation: 63
I have a simple AWS SAM setup with a Go lambda function. It's using https://github.com/aws/aws-sdk-go-v2 for dealing with DynamoDB, the endpoint is set via environment variables from the template. (Here: https://github.com/abtercms/abtercms2/blob/main/template.yaml)
My problem is that I can't get my lambda to return anything from DynamoDB, as a matter of fact I don't think it can reach it.
{
"level":"error",
"status":500,
"error":"failed to fetch item (status 404), err: operation error DynamoDB: GetItem, exceeded maximum number of attempts, 3, https response error StatusCode: 0, RequestID: , request send failed, Post \"http://127.0.0.1:8000/\": dial tcp 127.0.0.1:8000: connect: connection refused",
"path":"GET /websites/abc",
"time":1658243299,
"message":"..."}
I'm able to reach the local DynamoDB just fine from the host machine.
Results were the same both for running DynamoDB in docker compose and via the .jar file, so the problem is not there as far as I can tell.
Also feel free to check out the whole project, I'm just running make sam-local
and make curl-get-website-abc
above. The code is here: https://github.com/abtercms/abtercms2.
Upvotes: 3
Views: 851
Reputation: 911
Both sam local start-api and local dynamo run with docker; And by default docker isolates network, and the challenge here will be to make them work together.
I highly recommend to read this answer to a related question.
The easiest way here will be to put those containers on the host
network:
configure local dynamo
#dynamo docker compose
version: "3.8"
services:
dynamodb-local:
network_mode: "host" # HERE
command: "-jar DynamoDBLocal.jar -sharedDb -dbPath ./data"
image: "amazon/dynamodb-local:latest"
container_name: dynamodb-local
ports:
- "8000:8000"
volumes:
- "./docker/dynamodb:/home/dynamodblocal/data"
working_dir: /home/dynamodblocal
configure the db client with the url http://127.0.0.1:8000
import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-lambda-go/lambda"
)
func Handler(ctx context.Context, event *MyEvent) (*string, error) {
var LocalEndpoint = "http://127.0.0.1:8000"
cfg, err := config.LoadDefaultConfig(ctx)
client := dynamodb.NewFromConfig(cfg, func(o *dynamodb.Options) {
o.EndpointOptions.DisableHTTPS = true
o.BaseEndpoint = &LocalEndpoint
})
//...do stuff
}
func main() {
lambda.Start(Handler)
}
start local dynamo
docker compose up
start local api
sam local start-api --docker-network=host
Upvotes: 0