Skip to content

fix(local): make port publishing usable when SAM CLI runs in a container - #9290

Merged
bnusunny merged 8 commits into
aws:developfrom
bnusunny:fix/dind-container-host-interface
Nov 16, 2026
Merged

bnusunny merged 8 commits into
aws:developfrom
bnusunny:fix/dind-container-host-interface

Conversation

@bnusunny

@bnusunny bnusunny commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Which issue(s) does this change fix?

#2837

Why is this change necessary?

When SAM CLI runs inside a container (the docker-out-of-docker setup people use with Compose), the Lambda RIE port is published by the container engine (Docker or Finch) on that engine's host, while SAM CLI binds and resolves addresses in its own network namespace. Those are different machines as far as addresses are concerned, and three separate things go wrong because of it. I reproduced all of them on 1.166.2 and posted the full matrix in #2837:

# --docker-network --container-host --container-host-interface Before
A (none) host.docker.internal (default 127.0.0.1) 502, timeout naming neither flag
B (none) host.docker.internal 0.0.0.0 200
E (none) (default localhost) 0.0.0.0 502
F host host.docker.internal (default) 502 (the reporter's flags)
H user network host.docker.internal 240.10.0.1 (bridge gateway) crash: NoFreePortsError
  1. Arm H — find_free_port() probes the requested interface with a local bind(). A daemon-host address that does not exist inside SAM CLI's container fails with EADDRNOTAVAIL for every candidate, so all 4000 ports are reported busy when none of them are:

    samcli.local.docker.exceptions.NoFreePortsError: No free ports on the host machine from 5000 to 9000
    

    This is what forces --container-host-interface 0.0.0.0 as the only working value, which publishes the RIE invoke endpoint on every interface of the machine running the container engine.

  2. Arms A, D, F — a non-loopback --container-host with the default --container-host-interface 127.0.0.1 is self-contradictory: the port is published where the named container host cannot reach it. The failure arrives 20 s later as Timed out while attempting to establish a connection to the container… increase this timeout by setting SAM_CLI_CONTAINER_CONNECTION_TIMEOUT, which names neither flag and points at a timeout that cannot help.

  3. Arms F and G — --docker-network host is accepted and does nothing. Container.create() special-cases the value to skip the attach, and network_mode appears nowhere in samcli/, so containers are created on the default bridge:

    HostConfig.NetworkMode: default
    attached networks:      bridge=240.10.0.3
    

    Users pass it expecting host networking, and conclusions in the issue thread were drawn from changing a flag that has no effect.

How does it address the issue?

  • samcli/local/docker/utils.py — an interface that does not exist in this network namespace cannot be probed from here, and a bind against local interfaces would say nothing about the daemon host anyway. So on "address not available" the probe stops instead of widening: it returns the candidate port unprobed and warns that it did, and the daemon's own bind decides whether the port is free. That warning deliberately asks for nothing — for a remote daemon no interface is both bindable here and publishable where --container-host can reach it, so telling the user to change the flag would contradict the other new warning. EADDRINUSE still scans the range as before. A named or literal address is resolved through socket.getaddrinfo before binding, so an IPv6 value is probed on an IPv6 socket instead of failing resolution on an AF_INET one and a scope id (fe80::1%eth0) survives into the bind; a value that does not resolve here is returned unprobed rather than costing a full scan. The empty interface ("all interfaces") is probed on AF_INET with bind(("", port)) and is not resolved at all: getaddrinfo(None, AI_PASSIVE) returns both wildcards and their order is platform-dependent (IPv4 first on Linux, IPv6 first on macOS), and on macOS — whose stacks are separate by default — an IPv6 wildcard bind succeeds while the IPv4 wildcard is taken, reporting free a port the engine then cannot publish. The short-circuit covers EADDRNOTAVAIL, its Winsock spelling WSAEADDRNOTAVAIL (10049, which is what errno carries on Windows because CPython's winerror_to_errno passes Winsock codes through unchanged), and EAFNOSUPPORT, which creating an AF_INET6 socket raises on a host booted with IPv6 disabled.
  • samcli/commands/local/cli_common/invoke_context.py — two startup warnings in __enter__ (alongside the existing --no-watch precedent): one when --container-host does not resolve to loopback while --container-host-interface does, naming both flags and what to pass; one when --docker-network host is supplied, saying it is ignored.

Handing back an unprobed port means a daemon-side collision is now possible where the local probe used to catch it, and Container.start used to mistranslate two of the three ways an engine reports one. That was fixed separately in #9294, which has now merged (1eee817), so the mapping this change depends on is on develop already. It was split out of this PR during review so that an error-taxonomy change to a handler every sam local command shares got reviewed on its own, and it had to land first: with this change alone, an interface that exists neither locally nor on the engine's host (a stale 192.0.2.1, say) stopped failing as Error: No free ports on the host machine from 5000 to 9000 and instead reached the engine, whose cannot assign requested address refusal escaped the unmapped handler as a raw docker.errors.APIError traceback. That ordering requirement is now satisfied, and the hands-on finding about that traceback is resolved by develop rather than by anything in this PR.

Verified against the original reproduction with the patched files mounted over an installed 1.166.2:

  • arm H: NoFreePortsError → HTTP 200, preceded by Cannot check whether ports are free on 240.10.0.1: that address does not exist on this machine…. --container-host-interface <bridge gateway> is now a working, non-exposing alternative to 0.0.0.0.

  • arm A: still 502 on this Linux engine, where a loopback-bound port genuinely is unreachable through host.docker.internal, but now preceded by
    --container-host is host.docker.internal while the Lambda container's port is published on 127.0.0.1, a loopback address of the machine running the container engine. If invocations time out while connecting to the container, this is the likely cause… Passing --container-host-interface with an address reachable from host.docker.internal, such as the bridge gateway, resolves it. 0.0.0.0 works too but publishes the container's unauthenticated invoke endpoint on every interface of the machine running the container engine.

    The message states a likely cause rather than a certain outcome, because whether a loopback-bound port is reachable through the given container host depends on the engine. --container-host's own help suggests host.docker.internal for running SAM CLI in a container on macOS, and that combination can work on Docker Desktop, which is not covered by this matrix — so promising a timeout would be wrong there and would push those users to 0.0.0.0 for no reason.

    Both new warnings and the find_free_port docstring are worded for "the container engine" rather than for Docker: SAM CLI drives Docker or Finch through get_validated_container_client, and either can be the engine publishing the port. A test asserts the warning names no single engine.

  • arm F: 200, preceded by --docker-network host has no effect and is ignored…

What side effects does this change have?

  • Both new checks warn rather than fail. A non-loopback container host with a loopback interface is not broken on every Docker setup, and --docker-network host is inert rather than harmful, so configurations that pass these flags today keep working exactly as they do now. Nothing becomes an error.
  • The container-host check resolves the hostname (socket.getaddrinfo, so IPv4 and IPv6 alike) and treats a name as loopback when any resolved address is, so a container host that legitimately points at loopback produces no warning. An unresolvable hostname is treated as non-loopback and warns, which is the right call — it is not reachable either.
  • find_free_port behaviour is unchanged when the interface exists locally, which is every host install. Only the errnos meaning "this address cannot be probed here at all" short-circuit — EADDRNOTAVAIL, its Winsock spelling, and EAFNOSUPPORT; EADDRINUSE scans the range as it always did. In the short-circuit case the returned port is unverified by design, and the warning says so: it states that the engine refuses the publish and the command fails naming that port. With fix(local): report a taken host port instead of a raw APIError #9294 on develop, that refusal is now mapped to a named PortAlreadyInUse or ContainerNotStartableException rather than a raw APIError.
  • --docker-network host still does not give host networking. Honouring it would mean every Lambda container sharing the host namespace and competing for RIE's fixed 8080, so warning is the safe half of the fix; if we want to support it, that deserves its own change.

Mandatory Checklist

  • Review the generative AI contribution guidelines
  • Add input/output type hints to new functions/methods
  • Write design document if needed (Do I need to write a design document?) — not needed, no new interface
  • Write/update unit tests
  • Write/update integration tests — these paths need SAM CLI running inside a container against a mounted daemon socket, which the integration suite has no harness for; covered by unit tests plus the manual matrix above
  • Write/update functional tests if needed
  • make pr passes
  • make update-reproducible-reqs if dependencies were changed — no dependency changes
  • Write documentation

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

@bnusunny
bnusunny requested a review from a team as a code owner September 27, 2026 04:39
Comment thread samcli/local/docker/utils.py Fixed

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..10ea681
Files: 4
Comments: 1

Comment thread samcli/local/docker/utils.py Resolved
@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from 10ea681 to f6e2baa Compare September 27, 2026 05:02

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..f6e2baa
Files: 4
Comments: 2

Comment thread samcli/local/docker/utils.py Resolved
@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from f6e2baa to c80ffa8 Compare September 27, 2026 05:16

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..c80ffa8
Files: 4
Comments: 2

Comment thread samcli/local/docker/utils.py Resolved
@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from c80ffa8 to 5d5b540 Compare September 27, 2026 05:35

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..5d5b540
Files: 4
Comments: 1

@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from 5d5b540 to 4a01860 Compare September 27, 2026 05:49

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..4a01860
Files: 4
Comments: 2

Comment thread samcli/local/docker/utils.py Resolved
Comment thread samcli/local/docker/utils.py Resolved
@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from 4a01860 to 7a4afbc Compare September 27, 2026 06:08

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..7a4afbc
Files: 6
Comments: 1

Comment thread samcli/local/docker/container.py Resolved

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 94ee3f3..c74ff48
Files: 4
Comments: 2

Comment thread samcli/local/docker/utils.py Resolved
Comment thread samcli/local/docker/utils.py Resolved
@aws-sam-tooling-bot

aws-sam-tooling-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🧪 Hands-on test: No problems observed in 8 scenarios

Commit aacecb4 · build LambdaToolingHandsOn-Docker:6deac287-f828-410b-a4d5-391fd65df349. The plan's scenarios ran on an isolated build host; a problem is reported only if it reproduced at least twice. Passing scenarios show only that these checks behaved as expected, not that the change is correct.

Scenarios

Scenario Planned check Result Runner's note
S1 Main fix (arm H): an interface address that doesn't exist on this machine (TEST-NET 203.0.113.1) fails bind with EADDRN… ✅ pass Head: find_free_port('203.0.113.1', 5000, 9000) returned port 7862 (in range) with one WARNING from samcli.local.docker.utils naming 203.0.113.1 and 'without checking it'; the warning does not mentio…
S2 Regression: EADDRINUSE must still scan and still end in NoFreePortsError when every port is really busy, both for 127.0… ✅ pass Head and base behave the same: all ports held on 127.0.0.1 and on 0.0.0.0 (probed as '') both end in NoFreePortsError; free ranges for '' and 127.0.0.1 return in-range ports silently. 'without checki…
S3 IPv6 and odd values: ::1 is now bound on an AF_INET6 socket (related to dismissed finding lt-fcea1914a5c5), an unresolv… ✅ pass IPv6 is disabled in this sandbox (/proc/net/if_inet6 empty, disable_ipv6=1, AF_INET6 bind to ::1 gives errno 99), so the IPv6-loopback success path could not be shown; the fallback path was. Head: ::…
S4 Regression with Docker: a plain sam local invoke with default flags (container host localhost, interface 127.0.0.1) sti… ✅ pass Default 'sam local invoke' (run as samdev, the entry point the SAM_CLI_DEV=1 install provides) exits 0 with {"statusCode": 200, "body": "ok"} on head and base; new-warning grep count is 0 on both.
S5 New startup warning for a non-loopback --container-host with the default loopback interface, and no warning when the in… ✅ pass Head s5a (--container-host host.docker.internal, default interface): exactly one warning '--container-host is host.docker.internal while the Lambda container's port is published on 127.0.0.1...' prin…
S6 End-to-end check of arm H with Docker: a non-local --container-host-interface. The base dies with NoFreePortsError; the… ✅ pass --container-host-interface 203.0.113.1 with Docker. Base: exit 1, 'Error: No free ports on the host machine from 5000 to 9000'. Head: exit 1, no 'No free ports'; the 'without checking it' warning (po…
S7 Checks the PR's claim that --docker-network host is ignored (containers stay on the bridge network), and that the new w… ✅ pass start-lambda --docker-network host --warm-containers EAGER: on both head and base the warm container reports mode=bridge nets=bridge, confirming the flag has no effect. Head log contains '--docker-ne…
S8 Runs the PR's updated unit tests for the two changed modules, including the warn-once, Winsock errno and IPv6-socket te… ✅ pass pytest of tests/unit/local/docker/test_utils.py and tests/unit/commands/local/cli_common/test_invoke_context.py on head: 125 passed in 3.32s, exit 0.
Runner's notes in full
  • S1: Head: find_free_port('203.0.113.1', 5000, 9000) returned port 7862 (in range) with one WARNING from samcli.local.docker.utils naming 203.0.113.1 and 'without checking it'; the warning does not mention --container-host-interface (count 0). Base: 'RESULT NoFreePortsError No free ports on the host machine from 5000 to 9000', no warning.
  • S2: Head and base behave the same: all ports held on 127.0.0.1 and on 0.0.0.0 (probed as '') both end in NoFreePortsError; free ranges for '' and 127.0.0.1 return in-range ports silently. 'without checking it' count is 0 in all head logs. No regression.
  • S3: IPv6 is disabled in this sandbox (/proc/net/if_inet6 empty, disable_ipv6=1, AF_INET6 bind to ::1 gives errno 99), so the IPv6-loopback success path could not be shown; the fallback path was. Head: ::1, no-such-host.invalid and a 64-char label each return an in-range port with the 'without checking it' warning in 0.00s, exit 0, no traceback. Base: all three end in 'RESULT NoFreePortsError' (the 64-char label gives NoFreePortsError, not a UnicodeError traceback).
  • S5: Head s5a (--container-host host.docker.internal, default interface): exactly one warning '--container-host is host.docker.internal while the Lambda container's port is published on 127.0.0.1...' printed before the container starts, containing 'likely cause' and 'unauthenticated invoke endpoint'. s5b (interface 0.0.0.0) and s5c (localhost/127.0.0.1) have count 0; s5c returns statusCode 200. s5a/s5b exit 1 with 'Error: [Errno -2] Name or service not known' because host.docker.internal does not resolve on this Linux host; base fails identically (exit 1) and shows no warning in any of the three logs.
  • S6: --container-host-interface 203.0.113.1 with Docker. Base: exit 1, 'Error: No free ports on the host machine from 5000 to 9000'. Head: exit 1, no 'No free ports'; the 'without checking it' warning (port 7779), then a short message, no Python traceback or APIError: 'Error: The container engine cannot publish the container's port on the requested interface (... failed to bind host port 203.0.113.1:7779/tcp: cannot assign requested address). Pass --container-host-interface with an address that exists on the machine running the container engine.' This does not reproduce the traceback concern of lt-6e33eba28d0c/lt-58eaa80fb3be for the cannot-assign case; a daemon-side port collision (already in use) was not tested.
  • S7: start-lambda --docker-network host --warm-containers EAGER: on both head and base the warm container reports mode=bridge nets=bridge, confirming the flag has no effect. Head log contains '--docker-network host has no effect and is ignored...'; base log has no such line (count 0). Containers were cleaned up after kill (0 running).

🤖 Automated hands-on test — not a review approval · model claude-opus-5.5 · Kiro kiro-cli 2.33.1 · build LambdaToolingHandsOn-Docker:6deac287-f828-410b-a4d5-391fd65df349 · commit aacecb4

History (9)
Commit Result When (UTC) Build
aacecb4 No problems observed 2026-11-09 22:18 LambdaToolingHandsOn-Docker:6deac287-f828-410b-a4d5-391fd65df349
0d1ce1e No problems observed 2026-11-09 19:18 LambdaToolingHandsOn-Docker:282c78fb-828e-4da0-98af-04d6795ee254
0180d90 No problems observed 2026-11-09 18:31 LambdaToolingHandsOn-Docker:290bfe59-305c-4dc4-8e23-fb5c7f6756b3
72b64b0 No problems observed 2026-11-06 22:31 LambdaToolingHandsOn-Docker:07e0e900-c055-437f-904b-feb25430b2cc
0b8b890 Superseded 2026-11-06 22:24 LambdaToolingHandsOn-Docker:699e5248-7319-42c9-a5fd-eb222b308987
93d81de Problems reproduced: Unprobed --container-host-interface that the daemon cannot bind now ends in a r… 2026-11-03 17:40 LambdaToolingHandsOn-Docker:43f04972-f66d-4bb4-8459-d6140b3a0ad3
4ecd895 Problems reproduced: Non-local --container-host-interface now ends in a raw docker APIError tracebac…; find_free_port('') no longer probes all interfaces; it returns an unprobed port… 2026-11-03 16:20 LambdaToolingHandsOn-Docker:3116f648-d622-4dd7-a414-ea11a636fe90
16faedb Problems reproduced: Non-existent --container-host-interface now ends in a raw docker APIError trace…; find_free_port lets UnicodeError escape for an un-encodable interface (64-char … 2026-11-03 15:24 LambdaToolingHandsOn-Docker:8db8856d-b9cf-49af-8f4a-d179bc414c4c
06c8300 Problems reproduced: Unavailable --container-host-interface now ends in a raw docker APIError traceb…; Daemon-side port collision on the unprobed port escapes as docker.errors.APIErr… 2026-11-03 00:03 LambdaToolingHandsOn-Docker:3b3a32f3-57ea-417b-8203-e7d91dc8d50e

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Hands-on test reproduced 2 new problems on commit 06c8300. Commands and evidence are in the hands-on comment.

  1. [REGRESSION] Unavailable --container-host-interface now ends in a raw docker APIError traceback and bug-report prompt instead of a clean 'Error:' line · medium · samcli/local/docker/container.py:456
  2. [BUG] Daemon-side port collision on the unprobed port escapes as docker.errors.APIError, not PortAlreadyInUse · medium · samcli/local/docker/utils.py:87

🤖 Automated hands-on test — not a review approval

Comment thread samcli/local/docker/utils.py Resolved
@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from 06c8300 to 16faedb Compare November 3, 2026 15:13

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Hands-on test reproduced 2 new problems on commit 16faedb. Commands and evidence are in the hands-on comment.

  1. [UX] Non-existent --container-host-interface now ends in a raw docker APIError traceback and 'unexpected error' bug-report prompt instead of a clean error · low · samcli/local/docker/container.py:456
  2. [REGRESSION] find_free_port lets UnicodeError escape for an un-encodable interface (64-char label); CLI now shows an 'unexpected error' traceback where base gave a one-line error · low · samcli/local/docker/utils.py:118

🤖 Automated hands-on test — not a review approval

Comment thread samcli/local/docker/utils.py Resolved

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Hands-on test reproduced 2 new problems on commit 4ecd895. Commands and evidence are in the hands-on comment.

  1. [BUG] Non-local --container-host-interface now ends in a raw docker APIError traceback instead of a clean error · medium · samcli/local/docker/container.py:456
  2. [REGRESSION] find_free_port('') no longer probes all interfaces; it returns an unprobed port with a misleading 'address does not exist' warning · low · samcli/local/docker/utils.py:117

🤖 Automated hands-on test — not a review approval

Comment thread samcli/local/docker/utils.py Resolved

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Hands-on test reproduced 1 new problem on commit 93d81de. Commands and evidence are in the hands-on comment.

  1. [UX] Unprobed --container-host-interface that the daemon cannot bind now ends in a raw docker APIError traceback and an 'unexpected error' bug-report prompt instead of a clean Error line · medium · samcli/local/docker/container.py:455

🤖 Automated hands-on test — not a review approval

@bnusunny
bnusunny requested a review from vicheey November 6, 2026 21:03
@bnusunny
bnusunny requested a review from reedham-aws November 6, 2026 21:03
When SAM CLI itself runs in a container, the Lambda RIE port is published by
the Docker daemon on the daemon's host, which is a different network namespace
from the one SAM CLI binds and resolves addresses in. Three problems follow,
all of them reported in aws#2837:

* find_free_port() probed the requested interface inside SAM CLI's own network
  namespace. An interface that does not exist locally (for example the docker
  bridge gateway) failed every candidate with EADDRNOTAVAIL and raised
  NoFreePortsError, reporting 4000 ports busy when none of them were. That
  interface cannot be probed from here at all, so it now returns a port
  unprobed and says so, and the daemon's own bind decides whether the port is
  really free. This makes --container-host-interface <bridge gateway> work as
  the narrow alternative to 0.0.0.0. Both numbers the condition arrives under
  are matched: POSIX EADDRNOTAVAIL and Winsock WSAEADDRNOTAVAIL (10049), which
  is what errno carries on Windows.

* A non-loopback --container-host combined with the default
  --container-host-interface 127.0.0.1 publishes the port where the given
  container host cannot reach it. The invoke then failed 20 seconds later with
  a connection timeout that named neither flag and suggested raising the
  timeout. SAM CLI now warns at startup, naming both flags and what to pass.

* --docker-network host was accepted and silently ignored: the value is
  special-cased to skip the network attach, and nothing applies host
  networking, so containers stay on the default bridge. SAM CLI now warns that
  the flag has no effect.

Both startup checks warn rather than fail: neither combination is broken on
every Docker setup, and working configurations that pass these flags today keep
running unchanged.

The free-port probe resolves the requested address before binding it, so an
IPv6 value is probed on an IPv6 socket rather than failing address resolution
on an AF_INET one, and an IPv6 scope id (fe80::1%eth0) survives into the bind.
Resolving once instead of per candidate also means a value that does not
resolve here is reported unprobed immediately rather than after a full scan.

The unprobeable-interface warning does not promise a named port-allocation
error: mapping the engine's refusal to PortAlreadyInUse lives in
Container.start, which this change does not touch.

Both new warnings and the find_free_port docstring are worded for "the container
engine" rather than for Docker, since SAM CLI drives Docker or Finch through
get_validated_container_client and either can be the engine publishing the port.
getaddrinfo idna-encodes the name before resolving it and raises UnicodeError
for a label over 63 characters. UnicodeError is a ValueError, not an OSError,
so switching the probe to getaddrinfo let a mistyped --container-host-interface
escape find_free_port as a traceback where it used to be a one-line error.

The same defect was fixed in _resolves_to_loopback earlier in this change; this
is the sibling path. The test uses a real 64-character label rather than a mock,
because the exception type is the whole point and a mock cannot show it.

Found by the hands-on runner on 16faedb.
…erface

An empty interface means "all interfaces", and the old bind(("", port)) probed
it for real. socket.getaddrinfo("") raises gaierror even with AI_PASSIVE, so
moving the probe to getaddrinfo sent the wildcard down the unprobeable path and
warned that an empty address "does not exist on this machine".

Converting an empty value to None with AI_PASSIVE resolves to the wildcard, so
the wildcard is probed again as it was before. AI_PASSIVE is ignored for any
non-empty host, and binding 0.0.0.0, 127.0.0.1, localhost and ::1 is unchanged.

Found by the hands-on runner on 4ecd895.
@bnusunny
bnusunny force-pushed the fix/dind-container-host-interface branch from 93d81de to 0b8b890 Compare November 6, 2026 22:12
@bnusunny

bnusunny commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto develop (0b8b890) — the conflict is cleared and this is ready for review again.

The conflict was #9294 landing. Both PRs added a test class at the same point in tests/unit/commands/local/cli_common/test_invoke_context.py — TestInvokeContext_initialize_all_functions_containers from #9294 and TestInvokeContextContainerNetworkingWarnings from this one. They test different things, so both are kept; nothing was dropped and no production code conflicted.

Two things this changes for reviewers:

  1. The merge-order requirement is satisfied. This PR needed fix(local): report a taken host port instead of a raw APIError #9294 to land first, and it has (1eee817). I have updated the description accordingly — it was still written in the future tense about it.
  2. The one open hands-on finding is resolved by develop, not by this PR. The runner reported that an unbindable --container-host-interface ends in a raw docker.errors.APIError traceback instead of a clean error. That was the known cost of the split: the mapping for it lives in Container.start, which is now on develop (container.py:492-497). Nothing in this PR changed to address it, and nothing needs to.

Gates on the rebased head: 9796 unit tests passing, coverage 94.10% against the 94% floor, ruff + black + mypy clean.

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Results

Reviewed: 5a90346..0b8b890
Files: 4
Comments: 1

… certainty

The warning fired for the configuration --container-host's own help suggests
for macOS (host.docker.internal with the interface left at 127.0.0.1) and told
those users invocations "will time out". Whether a loopback-bound port is
reachable through the given container host depends on the engine: it is not on
a Linux engine, which is where the reproduction matrix was measured, but that
combination can work on Docker Desktop.

The diagnosis and the remedy are unchanged; only the certainty is dropped. The
message now leads with "if invocations time out while connecting to the
container, this is the likely cause", so it no longer pushes a working macOS
setup towards 0.0.0.0 and its all-interfaces exposure for no reason.

A test asserts the message does not promise a timeout.
…y resolves first

getaddrinfo(None, AI_PASSIVE) returns both wildcards and their ORDER IS
PLATFORM-DEPENDENT: IPv4 first on Linux, IPv6 first on macOS. Taking the first
entry therefore probed a different family per platform. On macOS, whose stacks
are separate by default (ip6.v6only=1), a bind on the IPv6 wildcard succeeds
while the IPv4 wildcard is already taken, so the probe reported free a port the
engine then could not publish. Linux hid this because bindv6only=0 makes the
IPv6 wildcard bind fail when the IPv4 one is held.

An empty interface is now probed on AF_INET with bind(("", port)) and nothing is
resolved for it, which is exactly what this function did before it resolved
anything. getaddrinfo is kept for named and literal addresses, where picking the
family and carrying an IPv6 scope id is the whole point.

EAFNOSUPPORT joins the errnos that short the scan: creating an AF_INET6 socket
raises it on a host booted with IPv6 disabled, and like EADDRNOTAVAIL the answer
is the same for every candidate port, so scanning 1000 of them to end in
NoFreePortsError was wrong.

The probe socket is closed with `with` on the failing path too. It leaked before
on every candidate that did not bind, which surfaced as ResourceWarnings; the
suite now passes under -W error::ResourceWarning.

Tests: the empty-interface test no longer pins a candidate port, so it does not
fail on a machine already holding 3093 (reproduced, and it did). A second test
asserts the family and bind address through a mock, so the platform-ordering
regression is caught on every platform rather than only on macOS.

Reported by a macOS reviewer; items 1, 2 and 3 of that review.
… not loopback

_resolves_to_loopback(container_host) ran before the interface check, so every
sam local run paid a DNS lookup just to decide whether to warn. The interface is
normally an IP literal and costs a parse, so checking it first short-circuits the
lookup away for every run that cannot produce the warning.

Item 7 of the macOS review.
EAFNOSUPPORT joined the unprobeable errnos, but the warning still said the
address "does not exist on this machine, probably because the container engine
runs elsewhere". For an IPv6 --container-host-interface on a host booted with
IPv6 off, both halves are wrong: the address does exist, and the engine is
local. The warning now says the address cannot be probed from this machine and
offers both causes as possibilities rather than one as a likelihood.

Also adds the case that was missing: EAFNOSUPPORT is raised when the AF_INET6
socket is CREATED, so it never reaches bind, and no test covered that path.
… on Windows

EAFNOSUPPORT was added to UNPROBEABLE_ERRNOS by errno constant only, which is
the same gap WSAEADDRNOTAVAIL already covers for the other code. CPython's
winerror_to_errno returns a Winsock code unchanged apart from six low-numbered
ones, so a socket error on Windows carries 10047, never errno.EAFNOSUPPORT
(102 there). A Windows host with IPv6 off and an IPv6 --container-host-interface
therefore fell through to the full scan and ended in NoFreePortsError.

The new test case is parameterized over both spellings, so the Winsock value is
pinned on every platform rather than only where it can be reproduced.

@vicheey vicheey left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this, and for splitting out #9294.

Optional: ports returned unprobed aren't tracked, so two containers started in the same process (warm containers, several functions) can draw the same port and the second publish fails. Remembering the ones already handed out and redrawing would avoid that.

Nit: .partition("%")[0] in _resolves_to_loopback is redundant, since ipaddress has accepted scope ids since Python 3.9.

@bnusunny
bnusunny added this pull request to the merge queue Nov 16, 2026
Merged via the queue into aws:develop with commit c875dfb Nov 16, 2026
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants