docker容器和宿主机相互访问

当前此示例在win10 环境测试可用,其他操作系统环境有待求证

win/linux : docker.for.win.localhost 、 host.docker.internal
mac : docker.for.mac.localhost

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. This is for development purpose and does not work in a production environment outside of Docker Desktop.

You can also reach the gateway using gateway.docker.internal.

If you have installed Python on your machine, use the following instructions as an example to connect from a container to a service on the host:

  1. Run the following command to start a simple HTTP server on port 8000.

    python -m http.server 8000

    If you have installed Python 2.x, run python -m SimpleHTTPServer 8000.

  2. Now, run a container, install curl, and try to connect to the host using the following commands:

     $ docker run --rm -it alpine sh
     # apk add curl
     # curl http://host.docker.internal:8000
     # exit
    

I want to connect to a container from the host

Port forwarding works for localhost--publish-p, or -P all work. Ports exposed from Linux are forwarded to the host.

Our current recommendation is to publish a port, or to connect from another container. This is what you need to do even on Linux if the container is on an overlay network, not a bridge network, as these are not routed.

For example, to run an nginx webserver:

$ docker run -d -p 80:80 --name webserver nginx

To clarify the syntax, the following two commands both publish container’s port 80 to host’s port 8000:

$ docker run --publish 8000:80 --name webserver nginx

$ docker run -p 8000:80 --name webserver nginx

To publish all ports, use the -P flag. For example, the following command starts a container (in detached mode) and the -P flag publishes all exposed ports of the container to random ports on the host.

$ docker run -d -P --name webserver nginx

See the run command for more details on publish options used with docker run.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值