user14483828
user14483828

Reputation:

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. 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

Upvotes: 10

Views: 30200

Answers (2)

Hans Kilian
Hans Kilian

Reputation: 25622

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.

Upvotes: 21

CodeScale
CodeScale

Reputation: 3324

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

Upvotes: 7

Related Questions