Back

Technologies:

javascriptjavascript
node.jsnode.js
avatar
Tolerim
3 hours ago

Please ensure that your database server is running at `localhost`:`5432` before using SAM CLI.

To start a local API in WSL using SAM CLI and connect it to a Postgres docker container, I used the following commands:

sam local start-api --profile my-aws-profile --skip-pull-image -p 4000 -t template.yaml -n local.env.json
and

postgresql://postgres:[email protected]:5432/postgres?schema=SCHEMA
However, when I attempted to connect the SAM local API to the Postgres DB from a lambda function, I received an error message indicating that the server running the SAM API was unable to access the same network.

After researching possible solutions, I came across a suggestion to use the --docker-network flag with a setting of "host" to start the SAM local API, and to update the connection string host to be host.docker.internal.

Subsequently, I modified my startup command as follows:

sam local start-api --profile my-aws-profile --skip-pull-image --docker-network host -p 4000 -t template.yaml -n local.env.json
and my DB connection string as:

postgresql://postgres:my[email protected]:5432/postgres?schema=SCHEMA
However, despite these changes, I was unable to establish a connection between the SAM local API and the Postgres DB, and my lambda function eventually timed out.

Could you help me understand why this is happening? Thank you!

Answers(1)
avatar
Tolerim
3 hours ago
Verified Answer
It's possible that the issue is related to the way the Postgres container is set up. One thing you could try is to make sure that the container is listening on all interfaces, not just on localhost. Sometimes, the default Postgres configuration will only listen on localhost, which can cause issues when trying to access it from another container. To do this, you can modify the postgresql.conf file inside the Postgres container to include the following line:
Once you've made this change, you'll need to restart the Postgres container to pick up the new configuration. Assuming that you've made this change and restarted the container, you should be able to connect to it from your Lambda function using the same connection string that you posted:
If you're still having issues connecting to the database after making this change, it might be worth looking at the logs for the Postgres container to see if there are any errors being reported there. You might also want to try connecting to the container from outside of the SAM API using a tool like psql to make sure that the container is listening on the right interface and port.
;