Skip to content

No response from invoke container: SAM CLI running in a container cannot reach RIE unless --container-host-interface is set #2837

Open

Description

@SorsOps

Description:

Related to #2492

When running a docker-compose with an image that is using sam to run a local api, the api can never get a response from the lambda container. Everything works correctly when run locally not in a container.

I have read through all the answers in 2492 and tried the various permutations suggested, nothing has worked. There appeared to be no subsequent documentation follow up for getting this setup to work with docker.

Steps to reproduce:

DockerFile

FROM python:alpine
RUN apk add --no-cache --virtual build-deps build-base=0.5-r2 gcc=10.2.1_pre1-r3 bash=5.1.0-r0 && \
    pip install aws-sam-cli==1.23.0 && \
    apk del build-deps
COPY ./sam_entrypoint.sh /bin/sam_entrypoint.sh
RUN chmod +x /bin/sam_entrypoint.sh

WORKDIR /app
COPY ./node_modules /app/node_modules
COPY ./package.json /app/package.json
COPY ./template.yml /app/template.yml
COPY ./dist /app/dist
EXPOSE 3000 
ENTRYPOINT ["sh","/bin/sam_entrypoint.sh"]

sam_entrypoint.sh

#!/bin/bash
set -o errexit
/usr/local/bin/sam local start-api --debug \
  --template ./template.yml \
  --host 0.0.0.0 \
  --container-host host.docker.internal \
  --container-host-interface  127.0.0.1 \
  --docker-network host

Template.yml

AWSTemplateFormatVersion: "2010-09-09"
Transform: "AWS::Serverless-2016-10-31"
Description: "Automated lambda setup for api gateway"
Resources:
  res0:
    Type: "AWS::Serverless::Function"
    Properties:
      CodeUri: "./"
      Handler: "dist/index.handler"
      Runtime: "nodejs12.x"
      Timeout: 10
      Events:
        CatchAll:
          Type: "Api"
          Properties:
            Path: "/"
            Method: ANY
  res1:
    Type: "AWS::Serverless::Function"
    Properties:
      CodeUri: "./"
      Handler: "dist/index.handler"
      Runtime: "nodejs12.x"
      Timeout: 10
      Events:
        CatchAll:
          Type: "Api"
          Properties:
            Path: "/{proxy+}"
            Method: ANY

Docker-compose

version: '3.6'
services:
  sam_app:
    build: 
      context: .
      dockerfile: Dockerfile.test
    ports:
      - "3000:3000"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock  
    extra_hosts:
      - "host.docker.internal:host-gateway"

Observed result:

sam_app_1  | 
sam_app_1  |    SAM CLI now collects telemetry to better understand customer needs.
sam_app_1  |
sam_app_1  |    You can OPT OUT and disable telemetry collection by setting the
sam_app_1  |    environment variable SAM_CLI_TELEMETRY=0 in your shell.
sam_app_1  |    Thanks for your help!
sam_app_1  |
sam_app_1  |    Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html
sam_app_1  |
sam_app_1  | 2021-04-28 17:40:50,630 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
sam_app_1  | 2021-04-28 17:40:50,630 | Using config file: samconfig.toml, config environment: default
sam_app_1  | 2021-04-28 17:40:50,631 | Expand command line arguments to:
sam_app_1  | 2021-04-28 17:40:50,631 | --template_file=/app/template.yml --host=0.0.0.0 --port=3000 --static_dir=public --layer_cache_basedir=/root/.aws-sam/layers-pkg --container_host=localhost --container_host_interface=127.0.0.1      
sam_app_1  | 2021-04-28 17:40:50,704 | local start-api command is called
sam_app_1  | 2021-04-28 17:40:50,709 | No Parameters detected in the template
sam_app_1  | 2021-04-28 17:40:50,732 | 3 stacks found in the template
sam_app_1  | 2021-04-28 17:40:50,732 | No Parameters detected in the template
sam_app_1  | 2021-04-28 17:40:50,753 | 3 resources found in the stack
sam_app_1  | 2021-04-28 17:40:50,753 | No Parameters detected in the template
sam_app_1  | 2021-04-28 17:40:50,773 | Found Serverless function with name='res0' and CodeUri='./'
sam_app_1  | 2021-04-28 17:40:50,773 | --base-dir is not presented, adjusting uri ./ relative to /app/template.yml
sam_app_1  | 2021-04-28 17:40:50,773 | Found Serverless function with name='res1' and CodeUri='./'
sam_app_1  | 2021-04-28 17:40:50,773 | --base-dir is not presented, adjusting uri ./ relative to /app/template.yml
sam_app_1  | 2021-04-28 17:40:50,777 | No Parameters detected in the template
sam_app_1  | 2021-04-28 17:40:50,798 | No Parameters detected in the template
sam_app_1  | 2021-04-28 17:40:50,819 | Found '1' API Events in Serverless function with name 'res0'
sam_app_1  | 2021-04-28 17:40:50,819 | Found '1' API Events in Serverless function with name 'res1'
sam_app_1  | 2021-04-28 17:40:50,819 | Detected Inline Swagger definition
sam_app_1  | 2021-04-28 17:40:50,819 | Lambda function integration not found in Swagger document at path='/' method='x-amazon-apigateway-any-method'
sam_app_1  | 2021-04-28 17:40:50,819 | Lambda function integration not found in Swagger document at path='/{proxy+}' method='x-amazon-apigateway-any-method'
sam_app_1  | 2021-04-28 17:40:50,819 | Found '0' APIs in resource 'ServerlessRestApi'
sam_app_1  | 2021-04-28 17:40:50,819 | Removed duplicates from '0' Explicit APIs and '2' Implicit APIs to produce '2' APIs
sam_app_1  | 2021-04-28 17:40:50,819 | 2 APIs found in the template
sam_app_1  | 2021-04-28 17:40:50,825 | Mounting res0 at http://0.0.0.0:3000/ [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
sam_app_1  | 2021-04-28 17:40:50,825 | Mounting res1 at http://0.0.0.0:3000/{proxy+} [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
sam_app_1  | 2021-04-28 17:40:50,826 | You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You 
only need to restart SAM CLI if you update your AWS SAM template
sam_app_1  | 2021-04-28 17:40:50,826 | Localhost server is starting up. Multi-threading = True
sam_app_1  | 2021-04-28 17:40:50  * Running on http://0.0.0.0:3000/ (Press CTRL+C to quit)
sam_app_1  | 2021-04-28 17:41:20,791 | Constructed String representation of Event to invoke Lambda. Event: {"body": null, "headers": {"Accept": "*/*", "Host": "127.0.0.1:3000", "User-Agent": "insomnia/2021.2.2", "X-Forwarded-Port": "3000", "X-Forwarded-Proto": "http"}, "httpMethod": "GET", "isBase64Encoded": false, "multiValueHeaders": {"Accept": ["*/*"], "Host": ["127.0.0.1:3000"], "User-Agent": ["insomnia/2021.2.2"], "X-Forwarded-Port": ["3000"], "X-Forwarded-Proto": 
["http"]}, "multiValueQueryStringParameters": null, "path": "/v1/openapi.json", "pathParameters": {"proxy": "v1/openapi.json"}, "queryStringParameters": null, "requestContext": {"accountId": "123456789012", "apiId": "1234567890", "domainName": "127.0.0.1:3000", "extendedRequestId": null, "httpMethod": "GET", "identity": {"accountId": null, "apiKey": null, "caller": null, "cognitoAuthenticationProvider": null, "cognitoAuthenticationType": null, "cognitoIdentityPoolId": null, "sourceIp": "172.24.0.1", "user": null, "userAgent": "Custom User Agent String", "userArn": null}, "path": "/{proxy+}", "protocol": "HTTP/1.1", "requestId": "d9c5fa20-2328-43f7-b4d2-5a35028dfab1", "requestTime": "28/Apr/2021:17:40:50 +0000", "requestTimeEpoch": 1619631650, "resourceId": "123456", "resourcePath": "/{proxy+}", "stage": "Prod"}, "resource": "/{proxy+}", "stageVariables": null, "version": "1.0"}
sam_app_1  | 2021-04-28 17:41:20,791 | Found one Lambda function with name 'res1'
sam_app_1  | 2021-04-28 17:41:20,791 | Invoking dist/index.handler (nodejs12.x)
sam_app_1  | 2021-04-28 17:41:20,791 | Environment variables overrides data is standard format
sam_app_1  | 2021-04-28 17:41:20,791 | Loading AWS credentials from session with profile 'None'
sam_app_1  | 2021-04-28 17:41:20,803 | Resolving code path. Cwd=/app, CodeUri=/app
sam_app_1  | 2021-04-28 17:41:20,803 | Resolved absolute path to code is /app
sam_app_1  | 2021-04-28 17:41:20,803 | Code /app is not a zip/jar file
sam_app_1  | 2021-04-28 17:41:20,817 | Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-nodejs12.x:rapid-1.23.0.
sam_app_1  |
sam_app_1  | 2021-04-28 17:41:20,817 | Mounting /app as /var/task:ro,delegated inside runtime container
sam_app_1  | 2021-04-28 17:41:21,124 | Starting a timer for 10 seconds for function 'res1'
sam_app_1  | 2021-04-28 17:41:22,075 | Cleaning all decompressed code dirs
sam_app_1  | 2021-04-28 17:41:22,075 | No response from invoke container for res1
sam_app_1  | 2021-04-28 17:41:22,075 | Invalid lambda response received: Lambda response must be valid json
sam_app_1  | 2021-04-28 17:41:22 172.24.0.1 - - [28/Apr/2021 17:41:22] "GET /v1/openapi.json HTTP/1.1" 502 -

Expected result:

That the lambda can be executed correctly and a response received.

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

  1. OS: Windows 10
  2. sam --version: 1.23.0
  3. AWS region: us-east-1

Activity

  1. hoffa commented on Apr 30, 2021

    @hoffa
    Contributor

    Is your Docker daemon running locally? Could you try with --container-host-interface 0.0.0.0 (which will bind the container ports to all network interfaces) to ensure it's not an issue with port binding?

  2. added
    area/local/start-api
    on Apr 30, 2021
  3. SorsOps commented on May 3, 2021

    @SorsOps
    Author

    Hi @hoffa I've tested with --container-host-interface 0.0.0.0, at this point I can't even get a request to go through to the docker-compose container at that point. Trying

    http://0.0.0.0:3000/v1/openapi.json ,
    http://localhost:3000/v1/openapi.json
    http:/127.0.0.1:3000/v1/openapi.json

    from the host system is inaccessible

    image

  4. xazhao commented on May 3, 2021

    @xazhao
    Contributor

    Hi @Andrewx82 could you try the command without --docker-network option? The default bridge network should work for your case.

  5. SorsOps commented on May 4, 2021

    @SorsOps
    Author

    Hi @xazhao The call is now accessible and I see it being processed in the logs , however I see no response from the containers

    sam_app_1  | 2021-05-04 11:43:05,155 | Found one Lambda function with name 'res1'
    sam_app_1  | 2021-05-04 11:43:05,155 | Invoking dist/index.handler (nodejs12.x)
    sam_app_1  | 2021-05-04 11:43:05,155 | Environment variables overrides data is standard format
    sam_app_1  | 2021-05-04 11:43:05,155 | Loading AWS credentials from session with profile 'None'
    sam_app_1  | 2021-05-04 11:43:05,168 | Resolving code path. Cwd=/app, CodeUri=/app
    sam_app_1  | 2021-05-04 11:43:05,168 | Resolved absolute path to code is /app
    sam_app_1  | 2021-05-04 11:43:05,169 | Code /app is not a zip/jar file
    sam_app_1  | 2021-05-04 11:43:05,173 | Image was not found.
    sam_app_1  | Building image...........................................................................................................................................................................................................................................................................................................................................................
    sam_app_1  | 2021-05-04 11:44:41,985 | Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-nodejs12.x:rapid-1.23.0.
    sam_app_1  |
    sam_app_1  | 2021-05-04 11:44:41,985 | Mounting /app as /var/task:ro,delegated inside runtime container
    sam_app_1  | 2021-05-04 11:44:42,334 | Starting a timer for 10 seconds for function 'res1'
    sam_app_1  | 2021-05-04 11:44:43,246 | Cleaning all decompressed code dirs
    sam_app_1  | 2021-05-04 11:44:43,246 | No response from invoke container for res1
    sam_app_1  | 2021-05-04 11:44:43,247 | Invalid lambda response received: Lambda response must be valid json
    sam_app_1  | 2021-05-04 11:44:43 172.20.0.1 - - [04/May/2021 11:44:43] "GET /v1/openapi.json HTTP/1.1" 502 -
    
  6. xazhao commented on May 4, 2021

    @xazhao
    Contributor

    @Andrewx82 extra-host in your docker compose file is for Linux. Since your OS is Windows, I guess that is actually causing the issue. Can you try it without extra-host?
    Btw in your case, it seems there is no need to use --container-host-interface option since the default value should work.

  7. SorsOps commented on May 5, 2021

    @SorsOps
    Author

    Hi @xazhao

    I have changed the sam_entrypoint.sh to the following

    set -o errexit
    BASEDIR=$(pwd)
    /usr/local/bin/sam local start-api --debug \
      --template ./template.yml \
      --host 0.0.0.0 \
      # --docker-volume-basedir "${BASEDIR}" \
      --container-host host.docker.internal \
      # --container-host-interface  0.0.0.0 \
      # --docker-network host
    

    along with the docker-compose to

    version: '3.6'
    services:
      sam_app:
        build: 
          context: .
          dockerfile: Dockerfile.test
        ports:
          - "3000:3000"
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock  
    

    Still appears to be no response

    sam_app_1  | 2021-05-05 07:47:59,514 | Found one Lambda function with name 'res1'
    sam_app_1  | 2021-05-05 07:47:59,515 | Invoking dist/index.handler (nodejs12.x)
    sam_app_1  | 2021-05-05 07:47:59,515 | Environment variables overrides data is standard format
    sam_app_1  | 2021-05-05 07:47:59,515 | Loading AWS credentials from session with profile 'None'
    sam_app_1  | 2021-05-05 07:47:59,531 | Resolving code path. Cwd=/app, CodeUri=/app
    sam_app_1  | 2021-05-05 07:47:59,531 | Resolved absolute path to code is /app
    sam_app_1  | 2021-05-05 07:47:59,531 | Code /app is not a zip/jar file
    sam_app_1  | 2021-05-05 07:47:59,547 | Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-nodejs12.x:rapid-1.23.0.
    sam_app_1  |
    sam_app_1  | 2021-05-05 07:47:59,547 | Mounting /app as /var/task:ro,delegated inside runtime container
    sam_app_1  | 2021-05-05 07:47:59,823 | Starting a timer for 10 seconds for function 'res1'
    sam_app_1  | 2021-05-05 07:48:00,764 | Cleaning all decompressed code dirs
    sam_app_1  | 2021-05-05 07:48:00,765 | No response from invoke container for res1
    sam_app_1  | 2021-05-05 07:48:00,765 | Invalid lambda response received: Lambda response must be valid json
    sam_app_1  | 2021-05-05 07:48:00 172.20.0.1 - - [05/May/2021 07:48:00] "GET /v1/openapi.json HTTP/1.1" 502 -
    
  8. SorsOps commented on May 11, 2021

    @SorsOps
    Author

    @xazhao @hoffa

    Would it be possible to just get a simple example of the SAM CLI working in docker using a volume from the host? There is an implicit understanding in the docs that its possible, but I don't see a working example anywhere for reference

  9. xazhao commented on May 13, 2021

    @xazhao
    Contributor

    @Andrewx82 I was testing using configurations from this comment: #2436 (comment). After adding --container-host host.docker.internal it works. It looks pretty similar setup with your setup though.

  10. SorsOps commented on May 14, 2021

    @SorsOps
    Author

    @xazhao I can confirm that that does not work . See my bash entry script

    #!/bin/bash
    set -o errexit
    BASEDIR=$(pwd)
    /usr/local/bin/sam local start-api --debug \
      --template ./template.yml \
      -v $BASEDIR \
      --host 0.0.0.0 \
      --container-host host.docker.internal 
    

    I also tried with and without the -v option

    Can we just get an official example instead of saying that it is supposed to work ?

  11. xazhao commented on May 19, 2021

    @xazhao
    Contributor

    @Andrewx82 This is what I'm currently using.
    Dockerfile

    FROM amazon/aws-cli
    
    RUN yum -y update && \
        yum install -y python3 && \
        python3 -m pip install aws-sam-cli
    
    ENTRYPOINT [ "" ]
    

    docker-compose.yml

    services:
      testcase:
        build: .
        working_dir: $PWD
        command: sam local start-api --host 0.0.0.0 --container-host host.docker.internal
        ports:
          - 3000:3000
        volumes:
          - '$PWD:$PWD'
          - '/var/run/docker.sock:/var/run/docker.sock'`
    

    Then open another terminal and use the following command:
    curl localhost:3000/hello

    Please note: My development environment is macOS and I think mounting volume is different in Windows (Seems you already did properly). For your No response ... error, it usually happens when lambda function is not hosted on a container correctly.
    One thing you might try is see if you can resolve host.docker.internal to an IP address. For me, host.docker.internal resolves to 192.168.65.2. If I use this ip instead of host.docker.internal, it will work too.

  12. SorsOps commented on May 19, 2021

    @SorsOps
    Author

    @xazhao I've tried to align my files to be similar to yours
    aws-sam.zip

    It appears that something is happening here as I'm getting information about interacting with the lambda, however it doesn't seem like its reading the values correctly. For clarity I don't want to use volumes for this as I want to bake a docker image with the lambda

  13. sbhvt commented on May 20, 2021

    @sbhvt

    I'm having a very similar issue. I think that the root cause is related to the code path it is attempting to mount.

    In the output that @Andrewx82 posted earlier, you see this line: Mounting /app as /var/task:ro,delegated inside runtime container. '/app' is the WORKDIR and is the path within the container but it is not the path on the host, and the docker engine needs the path on host for mounting.

    In order to properly evaluate paths for mounts, the docker engine needs the path on the host of the docker engine. In @xazhao 's examples, this is accomplished because of the working_dir: $PWD line in the docker-compose file. Using the sample code that @xaxhao shared, I am able to reproduce the same error that @Andrewx82 shared by commenting out the working_dir: $PWD line from docker-compose.

    (Note that if using the exact code shared by @xazhao , the WORKDIR is "aws" instead of "app", but the issue is the same regardless.) Here's what you see logged when working_dir: $PWD is commented out:

    sam_app_1  | 2021-05-20 20:26:52,932 | Resolving code path. Cwd=/aws, CodeUri=/aws/hello_world
    sam_app_1  | 2021-05-20 20:26:52,932 | Resolved absolute path to code is /aws/hello_world
    sam_app_1  | 2021-05-20 20:26:52,933 | Code /aws/hello_world is not a zip/jar file
    ...
    

    In the use case of running from within VSCode devcontainers, which is one of the use cases mentioned in #2492, the option with working_dir: $PWD is not a feasible solution.

    I also tried this (working_dir commented out but passing $PWD to the --docker-volume-basedir parameter) :

    version: '3.6'
    services:
      sam_app:
        #working_dir: $PWD
        build:
          context: .
          dockerfile: Dockerfile
        ports:
          - "3000:3000"
        command: sam local start-api --host 0.0.0.0 --container-host host.docker.internal --debug --docker-volume-basedir $PWD
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock
          - $PWD:$PWD
    

    In that case, here is the the output:

    sam_app_1  | 2021-05-20 20:30:33,580 | --base-dir is not presented, adjusting uri hello_world/ relative to /aws/template.yml
    ...
    sam_app_1  | 2021-05-20 20:26:52,932 | Resolving code path. Cwd=<MY_LOCAL_PATH>, CodeUri=/aws/hello_world
    sam_app_1  | 2021-05-20 20:26:52,932 | Resolved absolute path to code is /aws/hello_world
    sam_app_1  | 2021-05-20 20:26:52,933 | Code /aws/hello_world is not a zip/jar file
    ...
    

    I looked at the codebase related to that area of code: resolve_code_path in samcli/lib/utils/codeuri.py. The calling code already resolved the codeuri parameter to an absolute path before calling that method. Judging by the output, it looks like this happens in when it logs --base-dir is not presented. It looks like if the CodeUri were a relative path (the raw value in the template itself) instead of the absolute path when that method was called (i.e. Resolving code path. Cwd=<MY_LOCAL_PATH>, CodeUri=./hello_world), then it would properly resolve the absolute path to code and therefore work to use the --docker-volume-basedir $PWD option. This would allow for the functionality as it existed in prior versions of SAM CLI using that --docker-volume-basedir option and correspond to the documentation on the usage of that parameter which says:

    If Docker is running on a remote machine, you must mount the path where the AWS SAM file exists on the Docker machine and modify this value to match the remote machine.

    Requiring the configuration to use working_dir doesn't seem a viable resolution to #2492, especially in light of how it conflicts with the documentation around the --docker-volume-basedir parameter. It seems also related to: #963 and #1834.

    The desired behavior being described in this issue, #2492, #963 and #1834 seem like they would be resolved if you used --base-dir with the value passed for --docker-volume-basedir or resolved the stack location from the outset using the --docker-volume-basedir parameter value.

  14. 87 remaining items

  15. tariromukute commented on Feb 15, 2023

    @tariromukute

    I was able to get sam working inside docker. It turns out when running the application using docker-compose the utilities base path has to be the working directory inside docker. My working directory was /var/task/. I appended that to the ContentUri: utilities-layer/ to ContentUri: /var/task/utilities-layer/ and I got the application working.

    I tried to find a way to make this dynamic. My attempt was to have the base path for the utilities as a parameter like ContentUri: !Join ["", [!Ref UtilitiesBasePath, 'utilities-layer/']]. However it turns out --parameter-overrides 'ParameterKey=UtilitiesBasePath, ParameterValue=/var/task/' doesn't work when running locally. But it works with sam deploy, see the discussion #1490.

    My work around was to have the default of the parameter set to /var/task/ since I expect to test my application locally using docker compose then during sam deploy I have to make sure to replace the base path with ./. I haven't tested the last bit yet though. Note: I had no issue when running sam local start-api on my local machine outside docker-compose.

  16. zahid-hussain-dev commented on Jul 2, 2025

    @zahid-hussain-dev

    Any resolution? I am also encountering the same issue with SAM.

  17. awilkins commented on Jul 14, 2025

    @awilkins

    The PR linked above seems to fix it, but hasn't been merged, partly because I stopped working with this particular set of components and didn't have time to work on it. I have no idea if the code has diverged enough to break the patch.

  18. bnusunny commented on Sep 27, 2026

    @bnusunny
    Contributor

    Triage update. I reproduced this with SAM CLI 1.166.2, and the root cause is narrower than this thread has assumed — it is a port-binding namespace mismatch, not a --docker-network problem. There is a configuration that works today, and three defects behind the confusion.

    Reproduction matrix

    SAM CLI 1.166.2 (from PyPI) running inside a container, Docker 25.0.16 on Linux, /var/run/docker.sock mounted, project mounted at the same path as on the host, --add-host host.docker.internal:host-gateway, plus a sibling container named sibling on the user network. One python3.12 function behind GET /hello, always --host 0.0.0.0. samcli/local/docker/container.py in that install is byte-identical to develop at 94ee3f3, so the line numbers below apply to both:

    # --docker-network --container-host --container-host-interface Result
    A (none, bridge) host.docker.internal (default 127.0.0.1) 502
    B (none, bridge) host.docker.internal 0.0.0.0 200
    C user network host.docker.internal 0.0.0.0 200, and sibling resolves by name
    D user network host.docker.internal (default 127.0.0.1) 502
    E (none, bridge) (default localhost) 0.0.0.0 502
    F host host.docker.internal (default 127.0.0.1) 502 — the OP's flag combination
    G host host.docker.internal 0.0.0.0 200
    H user network host.docker.internal 240.10.0.1 (the bridge gateway) crash, see defect 2

    (The OP was on Windows; arm F is their flag combination on Linux. Everything here is Linux + Docker 25, so treat the Docker Desktop specifics as untested.)

    On 1.166.2 the failing arms report

    Timed out while attempting to establish a connection to the container. You can increase
    this timeout by setting the SAM_CLI_CONTAINER_CONNECTION_TIMEOUT environment variable.
    The current timeout is 20.0 (seconds).
    

    rather than the older No response from invoke container wording in this issue's title — same failure. Note that the advice the message gives is a dead end here: no timeout value makes an unreachable address reachable.

    The discriminator is --container-host-interface in every arm, whatever --docker-network is set to. Both --container-host host.docker.internal and --container-host-interface 0.0.0.0 are required; either one alone fails (A, E).

    Why: with the default interface, SAM publishes the Lambda container's RIE port on the daemon host's loopback and then tries to reach it from inside its own container, which is a different network namespace — 127.0.0.1 there is not the host's 127.0.0.1. With 0.0.0.0 the port is published on all host interfaces, so host.docker.internal (the host-gateway address) reaches it. Measured in the passing arm:

    lambda container networks:  bridge=240.10.0.2  samverify_net=240.11.2.4
    lambda container ports:     {"8080/tcp":[{"HostIp":"0.0.0.0","HostPort":"8002"}]}
    

    The invoke never travels over the user network at all — it hairpins out to the host's published port and back in.

    Three corrections to the thread's folklore

    --docker-network is not the culprit — in any of its forms. Arm C passes with a user network and arm G passes with --docker-network host, both on the strength of the interface flag alone. The one fully working reference in this thread, @grahamlyons' example repo, carries --docker-network and --container-host-interface 0.0.0.0, and has done since its first commit (2021-12-03) — while the failing configuration he posted four months earlier had --container-host but no interface flag. That before/after sits inside this thread already; we just read it as being about --docker-network.

    Attaching the Lambda container to both bridge and the user network is intended, documented behaviour — and it does not break DNS. container.py L306-L309 connects it to both, and the --docker-network help says so explicitly: "an existing docker network for AWS Lambda docker containers to connect to, along with the default bridge network". In arm C the function resolved sibling to 240.11.2.2 from inside the Lambda container with no trouble (Docker 25). So the 2021 concern that the double attach breaks name resolution does not reproduce, nobody needs the fixed-IP workarounds described earlier in this thread, and the bridge-disconnect half of #3509 would be changing documented behaviour rather than fixing a bug.

    --docker-network host does not give you host networking. It is accepted, and then ignored. See defect 3 below.

    Defect 1: the default interface is silently incompatible with a non-loopback container host

    Passing --container-host <something other than localhost> while leaving --container-host-interface at its default 127.0.0.1 is a self-contradictory configuration that SAM CLI accepts and then fails on 20 seconds later, with a message that names neither flag and points at a timeout instead. That combination recurs throughout this thread.

    It is cheap to fix properly: when --container-host is not a loopback address and --container-host-interface was not set explicitly, either bind the published port somewhere the given container host can actually reach, or fail immediately saying so. Either would have closed this issue years ago.

    Defect 2: the free-port probe runs in the wrong network namespace

    L171 picks the RIE host port by attempting a bind on --container-host-interface inside SAM CLI's own namespace, while L253 publishes it on the daemon's host. When SAM CLI runs in a container those are different machines as far as addresses are concerned, so naming a host interface that does not exist inside the container fails every candidate port (arm H):

    File ".../samcli/local/docker/container.py", line 171, in __init__
      self.rapid_port_host = find_free_port(
    File ".../samcli/local/docker/utils.py", line 75, in find_free_port
      raise NoFreePortsError(f"No free ports on the host machine from {start} to {end}")
    samcli.local.docker.exceptions.NoFreePortsError: No free ports on the host machine from 5000 to 9000
    

    4000 ports reported busy, none of them actually busy.

    This matters beyond the confusing error, because binding RIE to the bridge gateway instead of 0.0.0.0 is the narrow, non-exposing configuration for this setup — and defect 2 is the only thing preventing it. I confirmed that by patching the probe in place (s.bind((network_interface, port)) → s.bind(("", port)), leaving the publish on the gateway address untouched) and re-running arm H: HTTP 200, with the port published on 240.10.0.1 and reachable from the SAM CLI container. So fixing the probe turns --container-host-interface <bridge gateway> into a working, tighter alternative to 0.0.0.0.

    Defect 3: --docker-network host is silently ignored

    The OP passed --docker-network host, and people since have read it as putting the Lambda container in the host network namespace. It does not. L306 special-cases the value host to skip the network attach — and nothing anywhere else implements the other half of that special case. network_mode does not appear in samcli/ at all (git grep network_mode -- samcli on develop returns nothing), so the container is created on the default bridge and the flag has no effect. Inspected under --docker-network host:

    HostConfig.NetworkMode: default
    attached networks:      bridge=240.10.0.3
    published ports:        {"8080/tcp":[{"HostIp":"0.0.0.0","HostPort":"5593"}]}
    

    Arms F and G are therefore just arms A and B with a dead flag attached, which is exactly what their results show. Note the flag's help text promises "an existing docker network … to connect to", and host is an existing docker network by name, so a user reading the help has no way to know this value is inert. Either honour it by setting network_mode="host", or reject it with an error. One consequence for the record: any conclusion in this thread that removing --docker-network host changed the outcome cannot be right as stated — the flag does nothing either way, so something else must have differed in those runs. That includes my own reading until I inspected the container.

    Where that leaves #3509

    #3509 invokes the Lambda container directly on the shared network at port 8080 instead of hairpinning through a published host port. That is still the better design — no published port, no all-interfaces exposure, no dependence on host.docker.internal — and it gets more attractive once you notice that the working configuration today requires publishing RIE on every host interface. It is not the only way to fix the 502 any more, though, and it still needs the trigger condition it was missing: it rewrites host and port whenever a user network is named, which breaks SAM CLI running on the host with --docker-network, as @awilkins said in the PR description himself.

    Question for the thread, since it decides whether that condition needs detection at all: is anyone running SAM CLI on the host while passing --docker-network <user network> so Lambda containers can reach Compose services? If that combination has real users, the fix must detect whether SAM CLI is itself inside the target network; if it does not, it can switch on the presence of a user network and stay simple.

    Working configuration today

    services:
      app:
        image: your-image-with-sam-cli   # or build: .
        working_dir: $PWD                # same path inside the container as on the host
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock
          - $PWD:$PWD
        extra_hosts:
          - "host.docker.internal:host-gateway"   # Linux; Docker Desktop provides it
        ports:
          - "3000:3000"
        command: >
          sam local start-api --host 0.0.0.0
          --container-host host.docker.internal
          --container-host-interface 0.0.0.0

    I ran that file as written (Compose v2.29.7, image = python:3.12-slim + pip install aws-sam-cli==1.166.2): curl localhost:3000/hello → 200.

    Both --container-host and --container-host-interface are load-bearing. Do not bother with --docker-network host — per defect 3 it does nothing. Keep --docker-network <your compose network> if your functions need to reach sibling services by name; it is not the problem. Also verified through Compose: adding a second service sibling and --docker-network <project>_default still returns 200, and the handler resolves sibling to its compose-assigned address. If your project is mounted at a path that differs from the host path, pass --docker-volume-basedir <host path> instead of relying on working_dir.

    ⚠️ --container-host-interface 0.0.0.0 publishes the Lambda RIE invoke endpoint on every interface of the Docker host, not just loopback — anything that can reach the host can invoke your functions. On a shared or internet-reachable dev host, restrict it at the firewall. Defect 2 above is what currently prevents the narrower --container-host-interface <bridge gateway IP>.

    Housekeeping

    I will retitle this issue to the binding defect specifically, so it stops absorbing unrelated mount and path reports.

    Neighbouring issues, described accurately rather than lumped together: #4589 (GitLab/DinD) and #5391 (Bitbucket) are the same class of problem — the address SAM CLI uses to reach RIE is not an address in its own namespace — but their daemon runs in a separate container, so host.docker.internal:host-gateway does not point at it and the working configuration above does not transfer; --container-host there has to name the daemon's own host. #7029 is a different defect: an empty /var/task, i.e. a mount problem, not a port problem. If that is your symptom, follow #7029 rather than this issue.

    For the record, the path-resolution half of the original report (CodeUri resolved before --docker-volume-basedir was applied, diagnosed by @sbhvt) was genuinely fixed by #4186, which shipped in v1.57.0 and is not in v1.56.0. Closing the whole issue on that fix was wrong, and @awilkins was right to flag it.

    Apologies for the long silence on this one.

  19. changed the title [-]No response from invoke container for Lambda inside docker-compose[/-] [+]No response from invoke container: SAM CLI running in a container cannot reach RIE unless --container-host-interface is set[/+] on Sep 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions