access host network in localstack lambda

access host network in localstack lambda

What is host network?

  • host is the actual computer on which the the docker is installed.
  • By default the docker can't access the network of host.
  • The docker container cannot be able to access the resources like MySQL database or any HTTP server which is running on host computer.
  • There will be some cases where we need to connect to the host network on which the docker is installed.

lambda funciton in localstack

  • While we develop serverless applications on AWS cloud we generally test the code by deploying on AWS, every time the code get's changed. It will increase the development cost as we are using the AWS resources it will charge for the consume resources.
  • To save the development cost we use localstack.
  • Let's say we deployed a lambda funciton on localstack. Everytime it invokes localstack creates a new docker container and runs the lambda funciton code.
  • By default docker didn't allow us to access the host network. so, we need to explicitly configure it.

localstack docker configuration to access host network

  • To allow localstack lambda docker container to access host network we need to set docker container network to host.
  • Let's do that with environment variable LAMBDA_DOCKER_NETWORK=host.
  • Let's see an example configuration of docker-compose for localstack.
version: '3.5'

services:
  localstack:
    container_name: localstack
    environment:
      - DEBUG=1
      - LOCALSTACK_HOSTNAME=localhost
      - TEST_AWS_ACCOUNT_ID=000000000000
      - AWS_DEFAULT_REGION=us-west-2
      - DOCKER_HOST=unix:///var/run/docker.sock
      - DATA_DIR=/tmp/localstack/data
      - KINESIS_STREAM_SHARDS=1
      - KINESIS_ERROR_PROBABILITY=0.0
      - KINESIS_STREAM_NAME=local-stream
      - KINESIS_PROVIDER=kinesalite
      - LAMBDA_DOCKER_NETWORK=host
    image: localstack/localstack:latest
  • Now, we can connect to host network. but we can't use localhost i.e 127.0.0.1 as it represents the current container IP.
  • To access the host computer use host.docker.internal

That's it folks. Stay connected for more articles.