Alpine 3.18搭配cURL 8.2.1不遵循.localhost域名的/etc/hosts配置
Alpine 3.18中cURL 8.2.1无视Docker extra_hosts配置的问题解决
问题描述
将Docker镜像更新至Alpine 3.18后,应用无法通过cURL向同一主机上的其他容器发送HTTP请求——此前通过Docker Compose的extra_hosts参数实现该功能。调试发现Alpine自带的cURL 8.2.1似乎无视/etc/hosts中的extra_hosts配置,但ping命令可正常解析域名。
环境配置
docker-compose.yml:
version: "3.8" services: test: image: alpine:3.18 extra_hosts: - example.localhost:host-gateway
调试步骤及结果
- 启动容器:
docker-compose run test sh
- 安装cURL:
apk add curl
- 查看cURL版本:
/ # curl --version curl 8.2.1 (aarch64-alpine-linux-musl) libcurl/8.2.1 OpenSSL/3.1.2 zlib/1.2.13 brotli/1.0.9 libidn2/2.3.4 nghttp2/1.55.1 Release-Date: 2023-07-26 Protocols: dict file ftp ftps gopher gophers http https imap imaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp ws wss Features: alt-svc AsynchDNS brotli HSTS HTTP2 HTTPS-proxy IDN IPv6 Largefile libz NTLM NTLM_WB SSL threadsafe TLS-SRP UnixSockets
- 执行cURL请求(失败):
/ # curl -v example.localhost * processing: example.localhost * Trying [::1]:80... * Immediate connect fail for ::1: Address not available * Trying 127.0.0.1:80... * connect to 127.0.0.1 port 80 failed: Connection refused * Failed to connect to example.localhost port 80 after 0 ms: Couldn't connect to server * Closing connection curl: (7) Failed to connect to example.localhost port 80 after 0 ms: Couldn't connect to server
- 确认
/etc/hosts配置正确:
/ # cat /etc/hosts 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 192.168.65.254 example.localhost 172.20.0.3 76a7dfa28161
- ping命令正常解析:
/ # ping example.localhost PING example.localhost (192.168.65.254): 56 data bytes 64 bytes from 192.168.65.254: seq=0 ttl=62 time=2.224 ms 64 bytes from 192.168.65.254: seq=1 ttl=62 time=0.731 ms 64 bytes from 192.168.65.254: seq=2 ttl=62 time=0.322 ms ^C --- example.localhost ping statistics --- 3 packets transmitted, 3 packets received, 0% packet loss round-trip min/avg/max = 0.322/1.092/2.224 ms
原因分析
cURL 8.0+版本默认启用了AsynchDNS特性,在Alpine的musl libc环境下,异步DNS解析会绕过本地/etc/hosts文件,直接发起DNS查询,导致无法读取extra_hosts配置的映射关系。而ping命令使用系统同步DNS解析,会优先读取/etc/hosts,因此可以正常解析。
解决方案
临时解决(单命令生效)
在cURL请求中添加--no-asynch-dns参数,禁用异步DNS解析,强制使用同步解析读取/etc/hosts:
curl -v --no-asynch-dns example.localhost
或者使用--resolve参数直接指定域名的IP映射,无需依赖/etc/hosts:
curl -v --resolve example.localhost:80:192.168.65.254 example.localhost
永久解决(全局生效)
在容器中创建cURL配置文件,默认禁用异步DNS解析:
- 创建
/etc/curlrc文件:
echo "--no-asynch-dns" > /etc/curlrc
- 后续所有cURL请求都会自动应用该配置,无需额外添加参数。
内容的提问来源于stack exchange,提问作者Maarten de Graaf
相关产品推荐
相关产品推荐

