set docker container listen only to localhost not 0.0.0.0

Viewed 3791

I want to run docker container with --network=host but it ignores the port and ip. I want run docker container in my host network while I want to limit this container to listen only on localhost or 127.0.0.l not 0.0.0.0 .

What should I do?

1 Answers

Don't use --network=host; it generally disables Docker's networking layer and is almost never necessary.

Set the process inside the container to listen on the special "all interfaces" address 0.0.0.0. If you don't, it can't be called at all from outside its own container.

When you publish the container's port, either using the docker run -p option or the Compose ports: setting, both take a host IP address as an optional parameter. If you set that address to 127.0.0.1 then the published port won't be reachable from anywhere other than non-container host processes.

docker run -d \
  -p 127.0.0.1:8000:8000    \  # tell Docker to only accept connections
                            \  # on the host localhost interface
  -e BIND_ADDR=0.0.0.0:8000 \  # tell the application to accept
                            \  # connections from "everywhere"
  my/image
Related