I just had a similar issue where my mongo instance got hacked (no valuable data on it) while I thought the port was securely behind ufw firewall.
It turns out that if you're running docker and have ufw as your firewall, docker inserts iptables rules that bypass ufw. e.g. When you run:
docker run -p 27017:27017 ...
Docker inserts the firewall rule (https://docs.docker.com/network/iptables/):
$ sudo /sbin/iptables -L DOCKER
target prot opt source destination
ACCEPT tcp -- anywhere 172.17.0.2 tcp dpt:27017
Which opens 27017 to the outside, so although you think everything is nice and secure behind ufw, it is not.
If everything that uses mongo is all on one machine, binding docker to 127.0.0.1 instead of the default 0.0.0.0 is one 1st step to prevent outside connections.
e.g. Instead of:
docker run -p 27017:27017 ...
Use:
docker run -p 127.0.0.1:27017:27017 ...
While this prevents non-local connections, it still doesn't prevent docker creating the rule. Therefore port 27017 is still technically open and if you delete the rule, docker will recreate it again.
You should certainly consider the other security measures above as well, but it was a bit of a shocker when I realized this can happen with docker and ufw, so watch out for this.
I'm not seeing too many great solutions either:
https://www.techrepublic.com/article/how-to-fix-the-docker-and-ufw-security-flaw/
https://github.com/chaifeng/ufw-docker
(e.g. what happens if you move it onto a different box years later and forget to apply the fix to iptables)