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"
http://127.0.0.1:3306/
via CLI or a GUI like PSequel. No need to use SSH.http://127.0.0.1:3306/
, I get the error Connection refused
.127.0.0.1
resolves to the docker container's localhost rather than my machine's localhost.host.docker.internal ... resolves to the internal IP address used by the host
http://host.docker.internal:3306/
, I get the error Name or service not known
.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.
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:
Environment
variable in template.yaml
under your resource property.
Properties:
Environment:
Variables:
DB_HOST: *your_database_url*
env.json
file with following configuration. {
"*Logical_ID of your resource*": {
"DB_HOST": "host.docker.internal"
}
}
env.json
as sam local invoke --env-vars env.json
.