Windows主机Docker容器访问固定IP物理设备的网络配置
Windows Docker容器访问192.168.0.5子网物理设备的解决方案
问题背景
在Windows主机上运行Docker Desktop,需让容器访问处于192.168.0.0/24子网的固定IP物理设备(192.168.0.5)。尝试端口开放因目标端口随机无效;配置ipvlan网络时,卡在Windows环境下parent参数设置(docker-compose不接受“Ethernet 8”这类带空格的网卡名称),导致容器无法连通目标设备。
当前配置信息
现有docker-compose.yml
version: "3.8" services: python-fastapi: container_name: fast_api build: context: Python dockerfile: Vision_fastAPI.Dockerfile ports: - "5001:5000" networks: - myVLan networks: myVLan: driver: ipvlan driver_opts: parent: host ipvlan_mode: l2 ipam: config: - subnet: 192.168.0.0/24
Ubuntu参考配置命令
docker network create -d ipvlan --subnet=192.168.0.0/24 --ip-range=192.168.0.0/24 -o ipvlan_mode=l2 -o parent=enp11s0f1 myVLan
Windows本地网卡信息
Ethernet adapter Ethernet 8: Connection-specific DNS Suffix: Description . . . . . . . . . . . : Lenovo USB Ethernet #4 Physical Address . . . . . . . . : 3C-18-A0-52-43-C1 DHCP Enabled . . . . . . . . . . : no Autoconfiguration Enabled . . . . : Yes IPv4 Address . . . . . . . . . . : 192.168.0.210(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : NetBIOS over Tcpip . . . . . . . : Enabled
解决方案
第一步:获取Windows网卡的正确标识(解决parent参数问题)
Windows下不能直接使用“Ethernet 8”作为parent参数,需获取网卡的GUID或ifIndex:
- 打开PowerShell,执行命令:
Get-NetAdapter | Select-Object Name, InterfaceDescription, ifIndex, InterfaceGuid
- 在输出中找到对应“Lenovo USB Ethernet #4”的网卡,复制其
InterfaceGuid(格式类似{xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx})或ifIndex(数字)。
方式一:使用docker run命令创建容器并连接ipvlan网络
- 先创建ipvlan网络:
docker network create -d ipvlan ` --subnet=192.168.0.0/24 ` --ip-range=192.168.0.100-192.168.0.200 ` -o ipvlan_mode=l2 ` -o parent="{你的网卡GUID}" ` myVLan
替换
{你的网卡GUID}为第一步获取的实际值,也可使用ifIndex数字,比如parent="5"
- 运行容器并连接该网络:
docker run -d ` --name fast_api ` --network myVLan ` -p 5001:5000 ` 你的镜像名称:标签
方式二:修正docker-compose配置
修改docker-compose.yml中的parent参数为网卡GUID或ifIndex,同时补充必要IP配置:
version: "3.8" services: python-fastapi: container_name: fast_api build: context: Python dockerfile: Vision_fastAPI.Dockerfile ports: - "5001:5000" networks: myVLan: ipv4_address: 192.168.0.101 # 指定容器在子网内的固定IP,避免与现有设备冲突 networks: myVLan: driver: ipvlan driver_opts: parent: "{你的网卡GUID}" # 替换为实际GUID或ifIndex数字 ipvlan_mode: l2 ipam: config: - subnet: 192.168.0.0/24 ip_range: 192.168.0.100/28 # 限定容器IP范围,避免冲突
关键注意事项
- 确保容器IP不与现有设备(如192.168.0.5)的IP重复
- Windows下ipvlan网络需要Docker Desktop处于Windows容器模式(若之前用Linux容器需切换)
- 若子网无网关(如本地网卡配置中Default Gateway为空),无需添加网关配置
- 创建网络后测试连通性:
docker exec -it fast_api ping 192.168.0.5
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

