CodePark/ questions / Networking & ports
START PRACTICINGPRACTICE
Backend question · Docker › Networking & ports

On a cloud VM you run Postgres with docker run -p 5432:5432 postgres. The VM has a host firewall that blocks 5432. Why might the database still be reachable from the internet, and how do you fix it?

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.

  • -p binds 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.1 when only the host needs access.