Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access localhost from docker container

Tags:

java

docker

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


1 Answers

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.

Update, May 2024: While the above works, you should now use the --add-host option with the special host-gateway value to add a DNS entry to the container for the host. The common way is to use --add-host host.docker.internal=host-gateway as an option on docker run. That will allow you to access the host using the hostname host.docker.internal.

like image 179
Hans Kilian Avatar answered Apr 16 '26 23:04

Hans Kilian