连接到Docker中的服务,从交互式shell运行

假设我有以下容器:

docker run -i -t test/python3 /bin/bash

并在shell中运行以下命令:

python3 -m http.server 8080

如何从主机连接到此端口? 这可能吗?

您可以使用其专用IP直接连接到容器。 要发现它,在主机terminal上,您可以运行docker inspect --format '{{ .NetworkSettings.IPAddress }}' <container_id> 。 一旦容器运行(也来自主机),可以使用docker ps获取container_id。 一旦你有了这个IP,你可以直接访问它到你想要的端口。

另外,您可以select将容器端口发布到主机,因此您可以直接从localmachine访问localhost:8080 ,或者从任何其他可以与主机通信的机器(到足够的IP或主机名)访问。 要发布端口,您必须使用选项-p,作为docker run prompt help中的描述符:

 $ docker run --help (...) -p, --publish=[] Publish a container's port to the host format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort (...) 

因此,在这种情况下,您可以运行docker run -i -t -p 8080:8080 test/python3 /bin/bash ,例如,将容器的端口8080发布到本地计算机的相同数字端口(可以select任何其他尚未在您的主机中使用的)。 也可能你不需要以交互的方式运行容器,如果你不需要在里面执行任何进一步的操作(或者使用脚本执行这个操作),并直接运行你想要执行的命令: docker run -i -t -p 8080:8080 test/python3 python3 -m http.server 8080