首页 > 解决方案 > 如何从适用于 Linux 的 Windows 子系统内的 docker 容器内访问主机 localhost(例如 127.0.0.1:22334)

问题描述

假设我有一台服务器在 Windows 的 8000 端口上运行。我的 Docker 容器如何通过 127.0.0.1:8000 访问它?我也无法更改主机名,因为容器中的应用程序不在我的控制范围内。

我已经阅读了之前的讨论,但在 VB中使用“--network=host”作为容器来访问主机的网络,或者对 localhost 使用一些不同的 ip。但是,我在 Windows 上,Docker 在 Linux 的 Windows 子系统(来自 Windows 商店的 ubuntu)中运行,因此来自 Docker 容器的 localhost 与 --network="host" 不正确。从 Linux 的 Windows 子系统内部,我可以毫无问题地访问 127.0.0.1:8000。

例如,有一些 bash 文件执行以下操作

#!/bin/bash
set -x
# we get some file from the localhost
curl 127.0.0.1:22334/some_file.txt
# we build docker image
docker build --tag dockername --network=host dockerfiles/imagename

和一些像这样的docker文件

# This is a Dockerfile
FROM ubuntu:16.04 as installer
RUN apt-get update && apt-get install --no-install-recommends curl -y
RUN curl 127.0.0.1:22334/some_file.txt

我得到类似的东西

+ curl 127.0.0.1:22334/some_file.txt
here_we_get_some_file_content
+ docker build --tag dockername --network=host dockerfiles/imagename
Sending build context to Docker daemon  18.43kB
Step 1/30 : FROM ubuntu:16.04 as installer
 ---> 4a689991aa24
Step 2/30 : RUN apt-get update && apt-get install --no-install-recommends curl -y
 ---> Running in 72378a1be045
...
Step 3/30 : RUN curl 127.0.0.1:22334/some_file.txt
 ---> Running in 41a4c470337b
curl: (3) <url> malformed
The command '/bin/sh -c curl 127.0.0.1:22334/some_file.txt' returned a non-zero code: 3

标签: dockerlocalhostwindows-subsystem-for-linux

解决方案


推荐阅读