How to connect RDS instance when running SAM locally?
Asked Answered
M

2

5

I am using SAM (Serverless application model) to test Lambda functions locally that connect to an Aurora RDS instance in the cloud.

Using the following command:

sam local invoke "lambda function name" --event event.json

The Lambda function is being executed but when it comes to returning SQL results, it's returning null as output.

How can I configure the Docker container to communicate with the RDS instance?

Malliemallin answered 21/2, 2019 at 3:8 Comment(0)
V
5

As mentioned in the help for sam local invoke, you can connect your Docker container to an existing Docker network:

▶ sam local invoke --help                
...
  --docker-network TEXT           Specifies the name or id of an existing
                                  docker network to lambda docker containers
                                  should connect to, along with the default
                                  bridge network. If not specified, the Lambda
                                  containers will only connect to the default
                                  bridge docker network.

So, to list your Docker networks:

▶ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
25a03c8453a6        bridge              bridge              local
00de89cf09d0        host                host                local
41597d91a389        none                null                local

Then, to connect your Lambda function's Docker container to the host network:

▶ sam local invoke "lambda function name" --event event.json \
    --docker-network 00de89cf09d0

Note that you can also use the environment variable SAM_DOCKER_NETWORK:

▶ SAM_DOCKER_NETWORK=00de89cf09d0 sam local invoke "lambda function name" \
    --event event.json

As mentioned here.

Assuming the host network can access the RDS instance, that should fix your problem.

Voodooism answered 24/2, 2019 at 23:24 Comment(1)
Not working for me : "docker.errors.APIError: 400 Client Error: Bad Request ("container cannot be disconnected from host network or connected to host network")". I am using SAM CLI version 1.18.1 on Ubuntu 20Eliason
F
4

Pass --docker-network host to sam local invoke

sam runs your lambda/api in a docker container using default bridge network. The bridge network has limited access. You can either create a custom docker-network which has access to your RDS or use 'host' network which mimics your OS network.

When you install docker, it creates a network named host which you can assign to any docker container and grant it full access to all IP/port accessible by your OS.

Flite answered 23/9, 2020 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.