
September 09, 2026
12 min read
By Kokil Thapa | Last reviewed: September 2026
Every Ubuntu VPS you deploy for Laravel, WordPress, or a client portal sits on the public internet before your app code matters. To configure a firewall with UFW on Ubuntu, you define which ports accept traffic and block everything else by default. Uncomplicated Firewall (UFW) wraps iptables/nftables behind plain commands. That matters when you manage servers alone and cannot afford an SSH lockout during a Friday deploy. This guide walks through a production-safe sequence I use on real hosts, including web rules, IPv6, and recovery steps.
ufw enable, then verify with ufw status verbose before closing your session.For full-stack work spanning code, hosting, and hardening, see my Linux system administration services. The same baseline appears across sister sites I maintain with Deployer 7 and GitLab CI on shared EC2 infrastructure.
How do you configure a firewall with UFW on Ubuntu from scratch?
UFW ships with Ubuntu Server but stays inactive until you enable it. A fresh 24.04 LTS VPS often exposes SSH, and sometimes extra ports, with no host firewall applied. Your first job is to confirm what listens before you block anything.
Install and inspect UFW
On Ubuntu 22.04 and 24.04, UFW is usually pre-installed. If not, install it from the default repositories:
sudo apt update
sudo apt install ufw -y
sudo ufw version
sudo ufw status verbose Expect Status: inactive on a new machine. Check open listeners with sudo ss -tulpn. Note every port your stack needs: 22 for SSH, 80 and 443 for HTTP/S, 3306 only if MySQL must accept remote connections (usually it should not).
Set default policies
Production servers should deny unsolicited inbound traffic. Outbound traffic can stay allowed unless you run strict compliance workloads.
sudo ufw default deny incoming
sudo ufw default allow outgoing These defaults mean every new inbound connection is blocked until you add an explicit allow rule. That is the behaviour you want on a public VPS serving a Laravel app on Ubuntu with Nginx.
Allow essential services
Apply rules in this order. SSH always comes first.
- Allow OpenSSH (port 22 or your custom SSH port).
- Allow HTTP and HTTPS for web traffic.
- Allow any app-specific ports (Redis, queue workers) only if they must be reachable externally.
- Enable UFW and verify status.
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status numbered The OpenSSH profile reads /etc/services and maps to port 22. If you moved SSH to port 2222, use sudo ufw allow 2222/tcp instead. Never enable UFW until SSH is allowed. I have seen teams lock themselves out on staging boxes during hurried deploys.
What UFW rules should a production web server use?
A typical LEMP or LAMP stack on Ubuntu needs inbound 22, 80, and 443 only. Database ports, Redis, and Memcached should listen on 127.0.0.1 and stay blocked from the internet. Pair UFW with application-level hardening from the Ubuntu server security best practices guide.
Web server baseline rules
For Apache or Nginx serving PHP 8.3+ or Laravel 12/13:
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw limit OpenSSH
sudo ufw enable The limit directive adds rate limiting to SSH. It helps against brute-force attempts before fail2ban even kicks in. On Apache stacks, substitute 'Apache Full' for the Nginx profile. Both profiles open 80 and 443.
Restrict by IP when possible
Admin panels, database tunnels, and deployment hooks should not face the whole internet. UFW supports source IP restrictions:
sudo ufw allow from 203.0.113.50 to any port 22 proto tcp
sudo ufw allow from 198.51.100.0/24 to any port 22 proto tcp Use your office or home IP, or a VPN egress range. For Nepal-based teams on dynamic IPs, a bastion host or Tailscale node gives you a stable address to whitelist. Document allowed ranges in your runbook alongside Ubuntu server backup strategies so the next admin knows why a rule exists.
Application profiles and custom rules
UFW reads profiles from /etc/ufw/applications.d/. List available profiles with sudo ufw app list. Enable one with sudo ufw allow 'Profile Name'. For custom ports, specify protocol explicitly:
sudo ufw allow 8080/tcp comment 'Staging app'
sudo ufw deny 3306/tcp comment 'Block MySQL external' Comments appear in ufw status output and save hours during incident response. On booking platforms like Adventure Third Pole Trek, only web ports and SSH were exposed; queue workers ran locally.
How do you allow SSH without locking yourself out?
SSH lockout is the most common UFW mistake on Ubuntu VPS hosts. Cloud providers offer serial consoles or web terminals, but recovery takes time and stress. Prevention beats console access every time.
The two-session rule
Before running ufw enable, open a second SSH session to the same server. Complete all rule changes in session one. Test a new login in session two. If session two connects, your rules work. Only then close session one.
If you changed the SSH port in /etc/ssh/sshd_config, allow that port in UFW before restarting sshd. The order matters: UFW rule first, then sshd restart, then test.
Custom SSH port example
sudo ufw allow 49152/tcp comment 'Custom SSH'
sudo ufw delete allow OpenSSH
sudo systemctl restart ssh
sudo ufw enable Delete the old OpenSSH rule only after the new port works. Keep port 22 blocked once migration is confirmed. Scanning bots hammer port 22 constantly; a non-standard port cuts noise but is not a substitute for key-based auth and fail2ban.
Recovery if you are locked out
Most VPS providers (DigitalOcean, AWS Lightsail, local Nepali hosts) offer a browser-based console. Log in through the console, run sudo ufw disable or sudo ufw allow OpenSSH, then fix your rules. Some providers inject iptables rules outside UFW; check their docs if UFW commands seem ignored.
Generate strong credentials for recovery accounts using a secure password generator, but prefer SSH keys over passwords for server access. Keys plus UFW plus fail2ban form a practical baseline I deploy on legal-tech portals such as Court Marriage In Nepal.
How does UFW compare to iptables, nftables, and cloud firewalls?
UFW is a front end, not a separate packet filter. On modern Ubuntu it translates rules into nftables backend entries. You trade granular control for readability and safer defaults.
| Tool | Best for | Learning curve | Typical use case |
|---|---|---|---|
| UFW | Single VPS, small teams | Low | Laravel/WordPress server with SSH + web ports |
| iptables | Legacy scripts, fine control | High | Custom NAT, complex forwarding |
| nftables | New low-level rules | High | Distro defaults, advanced networking |
| Cloud security group | Provider-level filter | Medium | First line before traffic hits the VM |
In practice, use both a cloud security group and UFW. The cloud layer blocks traffic before it reaches your VM. UFW protects you if someone misconfigures the provider panel or you migrate between hosts. See the dedicated UFW firewall rules for web servers article for copy-paste rule sets.
Official reference: the Ubuntu community UFW documentation explains profile syntax and logging options. For nftables internals, the nftables project wiki covers what UFW generates under the hood.
IPv6 rules
Ubuntu enables IPv6 by default on many VPS images. UFW treats IPv4 and IPv6 separately unless you configure otherwise. Edit /etc/default/ufw:
IPV6=yes Then reload and mirror your IPv4 rules for IPv6:
sudo ufw allow 80,443/tcp
sudo ufw reload Neglecting IPv6 leaves your web stack reachable over v6 while v4 is filtered. Attackers scan both. After changes, run sudo ufw status verbose and confirm v6 entries appear.
How do you troubleshoot UFW when services stop working?
When a site goes down after enabling UFW, the firewall is a prime suspect. Work through checks before blaming PHP-FPM or Nginx.
Diagnostic commands
sudo ufw status numbered— lists rules with index numbers for deletion.sudo ufw show added— shows rules queued but not yet active.sudo journalctl -u ufw -e— UFW service logs.sudo tail -f /var/log/ufw.log— blocked packet log (requires logging enabled).sudo ss -tulpn— confirms the app listens on the expected port and interface.
Enable logging when debugging a stubborn block:
sudo ufw logging medium
sudo tail -f /var/log/ufw.log Try the failing connection from an external machine. Match the blocked port in the log to a missing allow rule. Disable logging back to low once resolved to reduce disk writes on small VPS plans (Rs 800–1,500/month, ~USD 6–11).
Common gotchas
Docker bypasses UFW. Docker inserts its own iptables rules that can expose ports regardless of UFW. Use Docker's iptables: false setting or publish ports carefully. See the Docker on Ubuntu install guide for networking notes.
Rule order and deletion. UFW processes rules top to bottom. Delete by number: sudo ufw delete 3. Numbers shift after each deletion, so always check status numbered again.
fail2ban integration. fail2ban modifies iptables directly. UFW and fail2ban coexist fine on Ubuntu when fail2ban uses the ufw action. Pair both as described in server hardening for Ubuntu web servers.
Managed MySQL. If MySQL 8.4 or 9.7 runs on the same host, bind to 127.0.0.1 in mysqld.cnf. Never expose 3306 publicly unless you use strict IP allowlists. The MySQL on Ubuntu setup guide covers bind-address defaults.
Pair UFW with ongoing maintenance
Firewall rules drift when teams add microservices, staging subdomains, or monitoring agents. Review rules quarterly. Remove stale comments and unused allows. Include UFW checks in your support and maintenance workflow alongside OS updates from the Ubuntu security updates guide.
For a full server bootstrap sequence, start with the Ubuntu server setup guide, then harden using the Ubuntu security hardening guide. Monitor open ports with the Ubuntu server monitoring guide after UFW is active.
When deploying PHP stacks, the Ubuntu server setup for PHP apps and LEMP stack on Ubuntu articles assume a filtered host. UFW is step one before Nginx TLS and PHP-FPM tuning.
Hosting choice affects your perimeter too. Shared cPanel hosts often manage firewalls for you. On a VPS from a domain and hosting provider, UFW is your responsibility. Budget Rs 1,000–3,000/month (~USD 7–22) for a basic VPS in Nepal; that price includes compute, not admin time.
If you prefer a managed approach, my Linux system administration service covers UFW, fail2ban, PHP-FPM, and deploy pipelines. Read more about my background on the about me page or browse the home page for other resources.
Key Takeaways
- Always allow SSH (or your custom SSH port) before running
ufw enable, and keep a second session open during changes. - Set
default deny incomingand explicitly allow only 22, 80, and 443 for standard web stacks. - Enable
IPV6=yesin/etc/default/ufwso IPv6 does not bypass your IPv4 rules. - Use
ufw limit OpenSSH, SSH keys, and fail2ban together rather than relying on any single control. - Check
ufw status numberedand/var/log/ufw.logfirst when a service stops responding after firewall changes. - Layer cloud security groups above UFW for defence in depth on production VPS hosts.
People Also Ask
Is UFW enabled by default on Ubuntu Server?
No. Ubuntu Server installs UFW but leaves it inactive until you run sudo ufw enable. Always configure allow rules first. A enabled firewall with no SSH rule will lock you out of remote administration.
Does UFW block outbound traffic by default?
No. The default outgoing policy is allow. Only incoming traffic is denied by default after you set ufw default deny incoming. Outbound restrictions require explicit deny rules and are uncommon on web servers.
Can UFW and fail2ban run together on Ubuntu?
Yes. fail2ban can use UFW as its banning backend through the ufw action configuration. UFW handles static port policy; fail2ban adds dynamic blocks against brute-force sources. Both belong in a hardened Ubuntu web server baseline.
How do I disable UFW temporarily for testing?
Run sudo ufw disable to stop filtering immediately. Use this only for short diagnostics on a trusted network. Re-enable with sudo ufw enable once you identify the missing rule. Never leave a public VPS unfiltered for convenience.
Next steps: harden your Ubuntu server perimeter
A correct UFW baseline takes ten minutes and prevents years of avoidable exposure. Configure a firewall with UFW on Ubuntu before you deploy application code, open provider panels to the world, or point a client domain at a fresh VPS. Start with deny-by-default, allow SSH and web ports, enable IPv6 parity, and verify from a second terminal. Then layer fail2ban, TLS, and monitoring.
Need help hardening a production host or recovering from a lockout? Contact us for Ubuntu server setup, firewall review, and ongoing maintenance. For related reading, see Ubuntu file permissions explained and essential Ubuntu terminal commands to round out your server admin toolkit.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

