KInGcC
KInGcC

Reputation: 372

Docker expose a port only to localhost

I want to restrict my database access to 127.0.0.1, so I executed the following command:

docker run -it mysql:5.5 -p 127.0.0.1:3306:3306 -name db.mysql 

But I have some confusion...

You can see here that only the port of 127.0.0.1 will be forwarded:

; docker ps
mysql:5.5     127.0.0.1:3306->3306/tcp   db.mysql

Interestingly, I cannot find this restriction in iptables:

; iptables -L
Chain FORWARD (policy DROP)
DOCKER     all  --  anywhere             anywhere

Chain DOCKER (2 references)                                                                                                                                                                  
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             192.168.112.2        tcp dpt:mysql

The source of this rule is anywhere.

Upvotes: 9

Views: 11134

Answers (1)

atline
atline

Reputation: 31584

The incoming traffic will go as next:

Incoming package to host's network -> use ip tables to forward to container

And, your restrict was not in iptables, it was in host's network, you just open 3306 bind on 127.0.0.1, not 0.0.0.0, so you of course not see anything in iptables. 127.0.0.1:3306:3306 means hostIp:hostPort:containerPort.

You could confirm it with netstat -oanltp | grep 3306 to see no 0.0.0.0 was there, so no foreign host could visit your host machine, thus also could not visit your container.

Upvotes: 11

Related Questions