I am running another API service on port 3001. When I try to call it from my Lambda local function, I get an error:
2018-01-11T21:16:09.065Z f3abec54-3c7f-1f83-ea7e-691abaf23ed5 (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejectionid: 2): Error: connect ECONNREFUSED 127.0.0.1:3001
The part of the code in question (using the Axios library):
axios.get('http://localhost:3001/hello').then(response => {
callback(null, {
statusCode: 200,
body: JSON.stringify({ message: JSON.stringify(response.data) })
})
})
It works fine if I use a publicly available endpoint, the issue is only with localhost.
This is due to the way Docker works.
When accessing localhost (or 127.0.0.1) from within a Lambda function running in SAM Local, you're actually accessing the docker network, not your laptop/machine.
Try using the main IP address for your local machine instead. If you're using Docker for Mac, you could also use the docker.for.mac.localhost hostname.
I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST
The Mac has a changing IP address (or none if you have no network access). From 17.06 onwards our recommendation is to connect to the special Mac-only DNS name docker.for.mac.localhost which will resolve to the internal IP address used by the host.
source: https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds
If anyone runs into this while using Docker for Windows, try replacing localhost (or 127.0.0.1) with host.docker.internal
If anyone runs into this while using Docker for Windows, try replacing localhost (or 127.0.0.1) with host.docker.internal
This works for mac too. Thanks.
For Linux use the IP address of the docker0 interface (172.17.0.1 by default).
Most helpful comment
This is due to the way Docker works.
When accessing localhost (or 127.0.0.1) from within a Lambda function running in SAM Local, you're actually accessing the docker network, not your laptop/machine.
Try using the main IP address for your local machine instead. If you're using Docker for Mac, you could also use the
docker.for.mac.localhosthostname.source: https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds