amazon-web-servicesdockeraws-lambdaamazon-rdsaws-sam-cli

How to connect a lambda to a database accessible locally on Mac's localhost when using sam


Background

What I have tried

aws ssm start-session --target <instance-id> --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters host="mydb.example.us-east-2.rds.amazonaws.com",portNumber="3306",localPortNumber="3306"

Minimal Working Example

I have created a MWE at https://github.com/bluprince13/sam-app-connect-to-host-localhost. Instead of trying to connect to a database, we can just run a Python server locally, and try to get the lambda to connect to it.

Question

References


Solution

  • The MWE provided looks correctly configured. The issue is with docker configuration. As OP could figure out, there was a dns override in the configuration. (Docker -> Preferences -> Docker Engine) was overridden. After removing it, everything worked fine with host.docker.internal.

    In general, to connect to the localhost of your host machine from a container you have to use host.docker.internal in mac and windows. Refer the SO post for configurations in other platforms. Specific to SAM in macOS, it is advisable to have the following, to avoid hard coding of parameters:

    1. Create an Environment variable in template.yaml under your resource property.
    
      Properties:
         Environment:
           Variables:
             DB_HOST: *your_database_url*
    
    1. Create an env.json file with following configuration.
       {
        "*Logical_ID of your resource*": {
            "DB_HOST": "host.docker.internal"
         }
       }    
    
    1. Run your SAM with the env.json as sam local invoke --env-vars env.json.