MySQL or PostgreSQL open to the internet: how to close the port and keep the app working
A database listening on a public address is attacked constantly with password guessing and known exploits. Almost every application uses the database from the same server, so it should not be reachable from outside at all.
Check where each database listens
Look at the address column: 127.0.0.1 is local only.
sudo ss -ltnp | grep -E ':(3306|5432)'MySQL and MariaDB: bind to localhost
Set bind-address in the server configuration and restart.
grep -rn 'bind-address' /etc/mysql/ sudo sed -i 's/^bind-address.*/bind-address = 127.0.0.1/' /etc/mysql/mysql.conf.d/mysqld.cnf sudo systemctl restart mysqlPostgreSQL: listen on localhost and limit who can connect
listen_addresses decides the interface; pg_hba.conf decides who may log in from where.
sudo -u postgres psql -c 'SHOW listen_addresses;' sudo -u postgres psql -c 'SHOW hba_file;' # in postgresql.conf: listen_addresses = 'localhost' sudo systemctl restart postgresqlBlock the ports in the firewall too
A second layer in case the configuration changes later.
sudo ufw deny 3306 sudo ufw deny 5432Reach the database from your computer with an SSH tunnel
No open port is needed: the tunnel runs over SSH.
ssh -L 5432:127.0.0.1:5432 user@SERVER_IP # then connect to localhost:5432Verify from outside
Only scan your own servers.
nmap -Pn -p 3306,5432 SERVER_IP # closed or filtered
Common mistakes
- Containers published with -p 5432:5432 ignore UFW: bind them to 127.0.0.1 (see the Docker and UFW guide).
- Leaving a remote user with host % after you close the port: delete it.
- Forgetting a second server that needs the database: use a private network.
How to undo it
Put the previous address back in the configuration and restart the service, then reopen the firewall rule for a specific address only.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.