Controlling Port Access with UFW

UFW (Uncomplicated Firewall) is a user-friendly front end for iptables designed to make managing a host-based firewall simpler. It’s available on Debian/Ubuntu and many other Linux distributions and provides a straightforward command-line interface to define policies that allow or deny network traffic. Controlling port access with UFW helps reduce your attack surface by explicitly permitting only the services and sources you trust while denying everything else by default.
This guide walks through the common tasks you’ll need to secure a server with UFW: installing UFW, configuring sensible default policies, allowing loopback traffic, permitting common public services (SSH, HTTP, HTTPS), restricting access to specific ports from trusted IPs or subnets, enabling the firewall safely, verifying active rules, and removing rules when needed. Along the way you’ll get practical tips to avoid locking yourself out (for example, always allow SSH before enabling UFW on a remote machine) and how to test rules after changes.
Prerequisites: a Linux server with UFW available (Ubuntu/Debian or similar) and sufficient privileges (root or sudo). After following this guide you’ll have a simple, maintainable firewall configuration that enforces least-privilege network access for your services.
So, let's get started…
Environment
| Hostname | alfian-lab |
|---|---|
| Operating System | Ubuntu 24.04 (Noble) |
| CPU | 2 vCPU |
| Memory | 2 GB |
| Disk | 40 GB |
| Private IP Address | 10.11.11.101 |
Setup UFW to Controlling Port Access
- Install UFW
# apt -y install ufw
# ufw status
- Set default to deny incoming and allow outgoing
# ufw default deny incoming
# ufw default allow outgoing
- Allow inncoming and outgoing to all port from loopback
# ufw allow in on lo comment 'loopback'
# ufw allow out on lo comment 'loopback'
- Allow incoming to basic port (ssh, https, and http) from all (public)
# ufw allow 815 comment 'ssh'
# ufw allow 443 comment 'https'
# ufw allow 80 comment 'http'
- Allow incoming to all port from specific ip/subnet
# ufw allow from 10.11.11.101 comment 'internal'
# ufw allow from 172.17.0.0/16 comment 'docker'
- Allow incoming to specific port from specific ip/subnet
# ufw allow from 10.11.11.102 to any port 8120 comment 'komodo'
# ufw allow from 172.18.0.0/16 to any port 5432 comment 'postgresql'
- Enable UFW
# ufw enable
# systemctl restart ufw
- Verification rule
# ufw status verbose
# iptables -L
- If you want delete rule
# ufw status verbose
# ufw delete allow from 10.11.11.102 to any port 8120
# ufw delete allow from 10.11.11.101
-- or --
# ufw status numbered
# ufw delete 7
References
Thank You.





