Connect from LocalStack lambda function to a database container using docker-compose service name

Viewed 853

I'm trying to connect from a lambda function in localstack to a database running in another container, but the lambda function can't resolve the service name.

version: '3.9'
services:
  db:
    image: mysql:5.7
    container_name: db
    restart: always
    environment:
      MYSQL_DATABASE: 'my_db'
      MYSQL_USER: 'admin'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - '3306:3306'
    expose:
      - '3306'
    volumes:
      - my-db:/var/lib/mysql
    networks:
      - development

localstack:
    image: localstack/localstack:latest
    hostname: localstack
    container_name: localstack
    environment:
      - AWS_DEFAULT_REGION=us-west-2
      - EDGE_PORT=4566
      - SERVICES=s3,lambda,apigateway,sqs
      - DEBUG=1
      - HOSTNAME_EXTERNAL=localstack
      - DB_HOST=db
      - DB_USER=admin
      - DB_PASSWORD=password
    networks:
      - development
    depends_on:
      - db
    ports:
      - '4566-4583:4566-4583'
    volumes:
      - "${TEMPDIR:-/tmp/localstack}:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

networks:
  development:

volumes:
  my-db:

The problem is that db can be resolved from the localstack container (e.g. docker-compose exec localstack ping db), but the lambda function says db is unresolvable.

I thought that you could add LAMBDA_DOCKER_NETWORK=development as an environment variable to the localstack service to connect the lambda functions to that network (see discussion), but when I do that I get an error message saying network development not found

docker.errors.NotFound: 404 Client Error for http+docker://localhost/v1.41/containers/f98dc74016048bc2295cf1bbf4af09c03e9a78faf5b1462f1130a76e0ca4f850/start: Not Found ("network development not found")

I also see this:

requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http+docker://localhost/v1.41/containers/1071c60ce1dd44800c38f726ef526388ce1a090bb1e394724cdfcbb76fb7e906/start
1 Answers

It looks like the way to connect to the correct network is to set this in the environment:

LAMBDA_DOCKER_NETWORK=<networkname>

So in the above example:

LAMBDA_DOCKER_NETWORK=development

documentation

Related