Linux guide

Configure a UFW Firewall Without Losing SSH Access

Establish a default-deny inbound policy, allow SSH first, add specific application ports, and audit the final ruleset.

By AIHOSTON Editorial Team6 min

Prerequisites

  • Sudo access
  • Knowledge of the active SSH port
  • Console or recovery access

Security note

Allow the actual SSH port before enabling UFW. If SSH uses a custom port, the OpenSSH profile may not match it.

Step 1

Inspect listening services

Identify the ports that are actually listening before creating firewall rules.

sudo ss -lntup

Step 2

Set baseline policies

Deny unsolicited inbound traffic and allow outbound traffic unless your environment requires stricter egress controls.

sudo ufw default deny incoming
sudo ufw default allow outgoing

Step 3

Allow SSH before enabling

Use the service profile for a standard setup or explicitly allow the custom port.

sudo ufw allow OpenSSH

Step 4

Allow required application traffic

For a public web server, allow HTTP and HTTPS. Do not expose database ports publicly unless a documented network design requires it.

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Step 5

Enable and audit

Enable UFW, verify numbered rules, then test SSH and application access from another session.

sudo ufw enable
sudo ufw status numbered

Troubleshooting

SSH is blocked
Use console access, disable or correct UFW, then explicitly allow the active SSH port before re-enabling it.
An old rule remains
List numbered rules and delete the exact rule number, then review the complete ruleset again.

Frequently asked questions

Should I expose a database port to the internet?

Prefer a private network, VPN, SSH tunnel, or tightly restricted source addresses. Public database exposure adds avoidable risk.

Related guides