Replicate --add-host behavior with extra_hosts
Description
In a docker run command, you can add multiple IP addresses for a single hostname. In a compose file, you can only set one IP per host.
docker run --rm --name tester --add-host myhost:0.0.0.1 --add-host myhost:0.0.0.2 alpine cat /etc/hosts
In a compose file, extra_hosts in long syntax won't pass validation if it sees duplicate keys. Short syntax will allow two hosts with the same IP, but overwrites any previous entries with the last entry for the same hostname.
services:
tester:
image: alpine
container_name: tester
extra_hosts:
- "myhost=0.0.0.1"
- "myhost=0.0.0.2"
command: cat /etc/hosts
I wonder: how will you use myhost host name inside container if it is set this way with more than one IP address ?
According to https://serverfault.com/questions/429839/assign-multiple-ips-to-1-entry-in-hosts-file a host file won't allow duplicate entries (but I can't find a reference documentation to confirm)
docker run -it --rm --name tester --add-host myhost:0.0.0.1 --add-host myhost:0.0.0.2 alpine sh
/ # apk add --update --no-cache curl
fetch https://dl-cdn.alpinelinux.org/alpine/v3.20/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.20/community/x86_64/APKINDEX.tar.gz
(1/10) Installing ca-certificates (20240705-r0)
(2/10) Installing brotli-libs (1.1.0-r2)
(3/10) Installing c-ares (1.28.1-r0)
(4/10) Installing libunistring (1.2-r0)
(5/10) Installing libidn2 (2.3.7-r0)
(6/10) Installing nghttp2-libs (1.62.1-r0)
(7/10) Installing libpsl (0.21.5-r1)
(8/10) Installing zstd-libs (1.5.6-r0)
(9/10) Installing libcurl (8.9.1-r0)
(10/10) Installing curl (8.9.1-r0)
Executing busybox-1.36.1-r29.trigger
Executing ca-certificates-20240705-r0.trigger
OK: 13 MiB in 24 packages
/ # curl --connect-timeout 10 -vI http://myhost
* Host myhost:80 was resolved.
* IPv6: (none)
* IPv4: 0.0.0.1, 0.0.0.2
* Trying 0.0.0.1:80...
* ipv4 connect timeout after 5000ms, move on!
* Trying 0.0.0.2:80...
* ipv4 connect timeout after 4998ms, move on!
* Failed to connect to myhost port 80 after 10001 ms: Timeout was reached
* closing connection #0
curl: (28) Failed to connect to myhost port 80 after 10001 ms: Timeout was reached
Hosts file allows multiple entries (both per hostname and per IP). It depends on the application (meaning whether or not they iterate over hosts in the file or just return the first match), but usually this means you can try one IP address and fallback to another if it fails. Obviously these requests both fail on the dummy IP address provided, but curl recognizes that there are two IPs for myhost, and falls back to the second options if the first fails.
ok, we could remove this restriction, but this also would mean one cannot override value anymore, which could be considered a regression. as "long syntax" is the canonical model I hardly can imagine how to address this