Sub topic 9
Limiting Database Access with a Firewall
Assume you know Linux networking, TCP ports, sudo, and how to manage a systemd service. This chapter uses Ubuntu's Uncomplicated Firewall (UFW). The same rule design applies to firewalld and nftables.
A firewall filters network traffic according to rules. For a database server, allow only the clients that need access. Do not expose PostgreSQL or MySQL to the entire internet.
Decide what should be reachable
PostgreSQL normally uses TCP port 5432. MySQL normally uses TCP port 3306. The database should listen on a private network address, and the firewall should allow the database port only from the application's private subnet.
| Database | Default TCP port | Example allowed source |
|---|---|---|
| PostgreSQL | 5432 | 10.0.0.0/24 |
| MySQL | 3306 | 10.0.0.0/24 |
The source network is written in CIDR notation. 10.0.0.0/24 includes addresses from 10.0.0.1 through 10.0.0.254. Replace it with the actual network used by your application.
The firewall is only one layer. The database configuration must also restrict listening addresses and client authentication.
Configure UFW safely
First allow SSH. Otherwise, enabling UFW can disconnect your administrative session. Then set a restrictive default and allow only the required database port from the private subnet.
sudo ufw allow OpenSSH
sudo ufw default deny incoming
sudo ufw default allow outgoing
# PostgreSQL
sudo ufw allow from 10.0.0.0/24 to any port 5432 proto tcp
# For MySQL instead, use:
# sudo ufw allow from 10.0.0.0/24 to any port 3306 proto tcp
sudo ufw enable
sudo ufw status numberedThe rule permits TCP connections from the application subnet, but not from other networks. If the application runs on one host, use that host's address with /32, such as 10.0.0.20/32, to narrow access further.
Verify the complete path
A successful connection requires all of these conditions:
- The database listens on the private address and correct port.
- The firewall allows the client's source address.
- PostgreSQL
pg_hba.confor MySQL account host rules allow the client. - The client uses the correct credentials and, where required, TLS.
Test from an approved application host, then confirm that an unapproved host cannot connect. Inspect the rules with sudo ufw status numbered. Remove an incorrect rule by number with sudo ufw delete NUMBER.
Exercise
A PostgreSQL server must accept connections from 10.0.0.20 but not from the rest of 10.0.0.0/24. What UFW rule should you add?
Show answer
sudo ufw allow from 10.0.0.20/32 to any port 5432 proto tcp