Docker docs:
Docker routes container traffic in the nat table, which means that packets are diverted before it reaches the INPUT and OUTPUT chains that ufw uses. Packets are routed before the firewall rules can be applied, effectively ignoring your firewall configuration.
Actually I believe host networking would be the one case where this isn’t an issue. Docker isn’t adding iptables rules to do NAT masquerading because there is no IP forwarding being done.
When you tell docker to expose a port you can tell it to bind to loopback and this isn’t an issue.