容器如何访问主机IP

通过 host.docker.internal ,如果linux不支持,那么在容器里,运行下面脚本

cat /host_ip_get.sh

#!/bin/sh
ip_address=$(ifconfig eth0 | grep 'inet addr:' | awk '{print $2}' | cut -d: -f2)
if [ -n "$ip_address" ]; then
    ip_prefix=$(echo $ip_address | cut -d. -f1-3)
    gateway_ip="${ip_prefix}.1"
    echo "**** Add host.docker.internal**** "
    echo "Host IP: $gateway_ip"
    if grep -q "host.docker.internal" /etc/hosts; then
        echo "host.docker.internal is ready"
    else
        echo "$gateway_ip host.docker.internal" | tee -a /etc/hosts > /dev/null
    fi
    echo "Updated /etc/hosts "
    cat /etc/hosts|grep host.docker.internal
else
    echo "no ip found at eth0"
fi

图示

2025-03-16T09:14:49.png