Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access webserver running on localhost from a docker container on a network?

I have the following system configuration:

  • Docker container running on user defined network
  • docker-machine (with VirtualBox on OS:X forwarding port 9000 to 9000)
  • Local webserver running on http://localhost:9000

I do not know how to make a basic http request against this webserver, from within my docker container.

To test this I am using:

docker exec testcontainer curl --data "foobaz=foo" http://{hostname}:9000/

where I have tried, for hostnames:

  • 'localhost'
  • '127.0.0.1'
  • '192.168.99.100' (docker-machine IP)

Each time I receive errors or timeouts. When I run the curl command locally (not in docker and on my host OS:X machine) I am able to successfully post the http request.

I cannot disconnect the docker container from my user-defined network. I also cannot add my webserver to that network, as it is not running in a container. Also, I know it is trivial to connect the other way (curl to a webserver running in a docker container) but this is not my use case.

How can I successfully route that http request from the docker container which is part of a user defined network to my localhost webserver?

like image 413
enderland Avatar asked Apr 19 '16 20:04

enderland


People also ask

How do I access docker localhost from another computer?

Docker manipulates iptables to expose the port(s) you specify on all the network interfaces present on your machine. From a different computer on your LAN, you should be able to just access http://LAN_IP:8080 where LAN_IP is PC1's LAN IP address (e.g. 192.168. 0. X).

How do I connect to a docker container locally?

To connect to a container using plain docker commands, you can use docker exec and docker attach . docker exec is a lot more popular because you can run a new command that allows you to spawn a new shell. You can check processes, files and operate like in your local environment.

How do I run a Web application in a docker container?

Head over to http://localhost:8888 and your app should be live. Note If you are using Docker Machine, you may need to open up another terminal and determine the container ip address using docker-machine ip default .


1 Answers

You can do this with the actual IP address of your local computer.

So for example, if your en0 IP is 10.100.20.32 on your host OS, you can run:

docker exec testcontainer curl --data "foobaz=foo" http://10.100.20.32:9000/

which will successfully allow you to make the http requests.

Note that if you are doing this from a container on the host docker network, this is trivial, as you can directly access localhost or 0.0.0.0 without having to use the actual machine IP.

like image 81
enderland Avatar answered Nov 07 '22 09:11

enderland