Reputation: 1115
I'm attempting to connect to a local Postgres server running as a docker container from my Lambda function.
I'm using the sam local invoke
call to do so.
For some reason, it seems that outgoing connection from SAM's docker container for the function is disabled.
I'm getting this error message:
"errorMessage": "(psycopg2.OperationalError) could not connect to server: Connection refused\n\tIs the server running on host \"localhost\" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\ncould not connect to server: Cannot assign requested address\n\tIs the server running on host \"localhost\" (::1) and accepting\n\tTCP/IP connections on port 5432?\n\n(Background on this error at: http://sqlalche.me/e/e3q8)",
Is there a way to enable a Lambda function call to a local docker database?
I have no issues running the connection code outside the Lambda function as standard Python code - so I'm sure my database is up, my code works, etc.
Upvotes: 3
Views: 2400
Reputation: 62
I resolve this by replacing localhost with host.docker.internal.
For example if you use psycopg2
conn = psycopg2.connect(host="host.docker.internal",port=5432, ...)
Upvotes: 1
Reputation: 21
Try running the command with —docker-network TEXT
per the AWS SAM CLI documentation.
I had a similar issue attempting to run sam local start-api
with a local Docker Postgres database and was getting connection refused
errors. I ran sam local start-api —docker-network host
and it resolved the issue.
This is a good post which helped me to understand more about Docker networks.
Hope this helps you and any others looking at this.
Upvotes: 2