简体   繁体   English

从 docker 容器访问 localhost

[英]Access localhost from docker container

I have an assignment to set up 3 docker container on localhost:8081, localhost:8082 and localhost:8083 which i've done succesfully.Then there is a last container that is a java app on localhost:8080 and it needs to send requests using HttpClient and HttpRequest to the other containers i've done this creating a bridge with "docker network create web_server --driver brigde" and im running the containers with --network web_server and this way they can communicate using the container names and it works.我有一个任务要在 localhost:8081、localhost:8082 和 localhost:8083 上设置 3 个 docker 容器,我已经成功完成了。然后有一个最后一个容器是 localhost:8080 上的 Java 应用程序,它需要发送请求将 HttpClient 和 HttpRequest 用于其他容器,我已经完成了此操作,使用“docker network create web_server --driver brigde”创建了一个桥接器,并使用 --network web_server 运行容器,这样它们就可以使用容器名称进行通信并且它可以工作. But my teacher told me to send the request to http://localhost:8081, 8082 etc. Is there a way to make containers access localhost?但是我的老师告诉我将请求发送到 http://localhost:8081、8082 等。有没有办法让容器访问 localhost? Im using docker for linux我在 linux 上使用 docker

On Linux containers, your can access the host using IP address 172.17.0.1 .在 Linux 容器上,您可以使用 IP 地址172.17.0.1访问主机。 So from inside your Java app you should be able to reach the other containers on 172.17.0.1:8081 , 172.17.0.1:8082 and 172.17.0.1:8083 .因此,从您的 Java 应用程序内部,您应该能够访问172.17.0.1:8081172.17.0.1:8082172.17.0.1:8083上的其他容器。 That's equivalent to using localhost:8081 , localhost:8082 and localhost:8083 on your host machine.这相当于在localhost:8081上使用localhost:8081localhost:8082localhost:8083

add --network="host" on your docker run command, then 127.0.0.1 in your docker container will point to your docker host.--network="host" docker run命令上添加--network="host" ,然后--network="host"容器中的 127.0.0.1 将指向您的 docker 主机。 (only work for docker on linux or windows container) (仅适用于 linux 或 windows 容器上的 docker)

For docker for mac or docker for windows just connect services using the host host.docker.internal instead of 127.0.0.1对于 docker for mac 或host.docker.internal for windows 只需使用主机host.docker.internal而不是127.0.0.1连接服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM