The port is open to every network interface, and Docker's own firewall rules can skip past the host firewall.
By default, -p 5432:5432 publishes the port on all host interfaces (0.0.0.0), not just on localhost. A network interface is one way into the machine, like the public network card or the local loopback. Docker makes publishing work by adding its own firewall rules (iptables on Linux). Those rules can run before host firewall tools such as ufw. So traffic reaches the container, even though the firewall seems to block port 5432.
Fixes, best first:
- Don't publish the database port at all. Let the API reach the database by name over a private Docker network.
- If the host itself needs access, bind the port to loopback only:
-p 127.0.0.1:5432:5432. Loopback (127.0.0.1) is reachable only from the same machine. - Also block access at the cloud provider's network level, for example with a security group.
- Use a strong database password.
Docker's docs warn that publishing ports is insecure by default for this reason.
-pbinds the port to all interfaces by default.- Docker's iptables rules can skip past firewalls like ufw.
- Don't publish internal services. Use a Docker network instead.
- Bind to
127.0.0.1when only the host needs access.
Read more
- Networking overview (https://docs.docker.com/engine/network/)docs.docker.com
- Docker security (https://docs.docker.com/engine/security/)docs.docker.com