7

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. But my teacher told me to send the request to http://localhost:8081, 8082 etc. Is there a way to make containers access localhost? Im using docker for linux

2 Answers2

16

On Linux containers, your can access the host using IP address 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. That's equivalent to using localhost:8081, localhost:8082 and localhost:8083 on your host machine.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • 1
    Indeed '172.17.0.1' accessed my docker's Ubuntu host, without the need of tweeking the networks, when 'host.docker.internal' clearly failed. – Grigoreas P. Feb 14 '22 at 12:00
3

add --network="host" on your docker run command, then 127.0.0.1 in your docker container will point to your docker host. (only work for docker on linux or windows container)

For docker for mac or docker for windows just connect services using the host host.docker.internal instead of 127.0.0.1

CodeScale
  • 3,046
  • 1
  • 12
  • 20
  • 1
    `--network=host` disables Docker's networking layer entirely. It will break the "normal" cross-container networking, for example as described in [Networking in Compose](https://docs.docker.com/compose/networking/). You shouldn't need it for routine Web applications. – David Maze Jun 17 '21 at 17:13
  • @DavidMaze wait... take a look at the "context". This is an assignment given by a teacher. We don't talk about running containers for production purposes. So get back to the context this option exists and afaik solves the initial problem. Downvote is a little bit overdone ;-) – CodeScale Jun 18 '21 at 07:26