6

I'd like to run a Docker container which only exposes it's ports INTERNALLY within the docker instance on the said host. This means I do NOT want it public.

Hows does one do this from the command line? The code below opens it publicly.

docker run -p 27017:27017 --name mongo mongo

3 Answers 3

5

If you execute:

docker run -p 27017:27017 --name mongo mongo

Then docker interprets that as:

docker run -p 0.0.0.0:27017:27017 --name mongo mongo

Which means that the port is accessible from the host, but also externally.

You can verify that by running nmap -p 27017 <host IP> from a different machine against your host. Port 27017 should show up as 'open'.

If you execute:

docker run -p 127.0.0.1:27017:27017 --name mongo mongo

Then the port is only accessible from the host.

You can verify that by running nmap -p 27017 <host IP> from a different machine against your host. Port 27017 should show up as 'closed'.

Finally, if you execute:

docker run --name mongo mongo

Then all ports will be local to the container.

Again, you can verify that by running nmap on your host against the container: nmap -p 27017 <container IP>. Port 27017 should show up as 'closed'.

2

the --expose-tag of Docker's run-command should provide you with what you want. From the documentation:


Publish or expose port (-p, --expose)

$ docker run -p 127.0.0.1:80:8080/tcp ubuntu bash

This binds port 8080 of the container to TCP port 80 on 127.0.0.1 of the host machine. You can also specify udp and sctp ports. The Docker User Guide explains in detail how to manipulate ports in Docker.

$ docker run --expose 80 ubuntu bash

This exposes port 80 of the container without publishing the port to the host system’s interfaces.


When you EXPOSE a port for a container it is accesible within the container's network only (bridge by default). This is useful for running multiple containers in a network and having them communicate, without publishing their ports externally (for example for security reasons).

0

If you run

docker run --name mongo mongo

other containers will be able to access mongo but ONLY if they know the ip of the mongo container but no outside the host access will be allowed

Also the following will prevent machines outside the host to access mongo

docker run -p 127.0.0.1:27017:27017 --name mongo mongo

still other containers can access it if they know the ip

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .