Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind docker container loopback to the host loopback

I pull a docker image (will use python 3 as an example)

docker pull python:3.6

Then I launch a docker container

docker run -it -p 127.0.0.1:8000:8000 python:3.6 bash

(note that here 127.0.0.1 in 127.0.0.1:8000:8000 allows to specify the destination, host IP but not the source)

So if I launch a server inside the container at 0.0.0.0:

python -m http.server 8000 --bind 0.0.0.0

then I can access the container's server from the host machine without any problem by going to http://127.0.0.1:8000 at the host machine

However if my docker server binds to 127.0.0.1 instead of 0.0.0.0:

python -m http.server 8000 --bind 127.0.0.1

then accessing http://127.0.0.1:8000 from the host does not work.

What's the proper way of binding the container's loopback 127.0.0.1 to the host loopback?

like image 972
Ilya Kharlamov Avatar asked May 13 '26 18:05

Ilya Kharlamov


1 Answers

What's the proper way of binding the container's loopback 127.0.0.1 to the host loopback?

On Linux, this can be done by configuring your Docker container to use the hosts network namespace, ie:

docker run --network=host

This only works on Linux because on Linux, your machine is the host, and the containers run as containers in your machines OS. On Windows/OSX, the Docker host runs as a virtual machine, with the containers running in the virtual machine, and so they can't share your machines network namespace.

like image 104
James Roper Avatar answered May 15 '26 11:05

James Roper