Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Configure a Firewall with UFW on Ubuntu

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.

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).

UFW Setup Workflow on Ubuntu1. Auditss -tulpn2. Defaultsdeny incoming3. AllowSSH + web ports4. Enableufw enableSafe enable checklist• Keep a second SSH session open• Allow SSH before ufw enable• Run ufw status verbose• Test from another terminal
Configure a firewall with UFW on Ubuntu: audit listeners, set defaults, allow required ports, then enable with a backup session open.

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.

  1. Allow OpenSSH (port 22 or your custom SSH port).
  2. Allow HTTP and HTTPS for web traffic.
  3. Allow any app-specific ports (Redis, queue workers) only if they must be reachable externally.
  4. 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.

UFW Port Policy for Web ServersInternetUFWdefault denyUbuntu VPS22 SSH80 HTTP443 HTTPS3306 DB6379 Redis11211 MemGreen = allowed inbound | Red = blocked from internet
Production UFW rules on Ubuntu: allow SSH and web ports; block database and cache ports from public access.

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.

Prevent SSH Lockout When Enabling UFWSession AApply UFW rulesSession BTest new loginBoth connected?Safe to enable UFWSession B fails?Fix rules in Session A — do not close it
Always keep two SSH sessions open when you configure a firewall with UFW on Ubuntu to avoid lockout.

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.

ToolBest forLearning curveTypical use case
UFWSingle VPS, small teamsLowLaravel/WordPress server with SSH + web ports
iptablesLegacy scripts, fine controlHighCustom NAT, complex forwarding
nftablesNew low-level rulesHighDistro defaults, advanced networking
Cloud security groupProvider-level filterMediumFirst 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).

UFW Troubleshooting FlowService unreachable?Check listenerss -tulpnCheck UFW rulesstatus numberedCheck logsufw.logAdd missing allow ruleufw allow port/tcpConfirm app binds 0.0.0.0 or :: before blaming UFW
When a service fails after UFW enablement, verify the listener, rule set, and block logs before changing application config.

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 incoming and explicitly allow only 22, 80, and 443 for standard web stacks.
  • Enable IPV6=yes in /etc/default/ufw so 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 numbered and /var/log/ufw.log first 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

UFW is Uncomplicated Firewall, a front end that wraps iptables or nftables behind plain commands. On a public VPS running Laravel, WordPress, or a client portal, it lets you define which ports accept traffic and block everything else by default. That matters when you manage servers alone and cannot afford an SSH lockout during a deploy.

Confirm open listeners with ss -tulpn, then set default deny incoming and allow outgoing. Allow SSH first, then HTTP and HTTPS, plus any app-specific ports only if they must be reachable externally. Run ufw enable only after SSH is allowed, and verify with ufw status verbose or ufw status numbered before closing your session. Keep a second SSH session open throughout.

No. Ubuntu Server installs UFW but leaves it inactive until you run ufw enable. Configure allow rules first, especially SSH, or you will lock yourself out of remote administration.

A typical LEMP or LAMP stack needs inbound SSH, port 80, and port 443 only. Use ufw allow OpenSSH, ufw allow Nginx Full or Apache Full, and ufw limit OpenSSH for rate limiting against brute-force attempts. Database ports, Redis, and Memcached should listen on 127.0.0.1 and stay blocked from the internet. Pair UFW with fail2ban and SSH keys for a practical hardened baseline.

Use the two-session rule: open a second SSH session before running ufw enable, apply all rules in the first session, then test login in the second. If you changed the SSH port in sshd_config, add the UFW allow rule for that port before restarting sshd. If you migrate to a custom port, confirm the new port works before deleting the old OpenSSH rule. Never enable UFW until SSH access is confirmed working.

No. After you set ufw default deny incoming, the default outgoing policy remains allow. Only unsolicited inbound traffic is blocked until you add explicit allow rules. Outbound restrictions require explicit deny rules and are uncommon on standard web servers.

UFW is a readable front end, not a separate packet filter; on modern Ubuntu it translates rules into nftables entries. iptables and nftables offer finer control but a steeper learning curve. Cloud security groups filter traffic before it reaches your VM. In practice, use both a cloud security group and UFW so you stay protected if a provider panel is misconfigured or you migrate hosts.

Ubuntu enables IPv6 by default on many VPS images, and UFW treats IPv4 and IPv6 separately unless configured otherwise. Set IPV6=yes in /etc/default/ufw, reload, and mirror your IPv4 web rules for IPv6, for example allowing ports 80 and 443 over TCP. Neglecting IPv6 leaves your stack reachable over v6 while v4 is filtered. Confirm v6 entries appear in ufw status verbose after changes.

Work through firewall checks before blaming PHP-FPM or Nginx. Run ufw status numbered to list rules with index numbers, ufw show added for queued rules, journalctl -u ufw for service logs, and ss -tulpn to confirm the app listens on the expected port and interface. Enable ufw logging medium and tail /var/log/ufw.log while testing from an external machine. Match blocked ports to missing allow rules, then set logging back to low once resolved.

Yes. fail2ban can use UFW as its banning backend through the ufw action configuration. UFW handles static port policy such as allowing SSH and web ports, while fail2ban adds dynamic blocks against brute-force sources. Pair ufw limit OpenSSH, SSH keys, fail2ban, and UFW together rather than relying on any single control. Both belong in a hardened Ubuntu web server baseline I deploy on production hosts.

Docker inserts its own iptables rules that can expose ports regardless of what UFW allows or denies. That means a container published to a host port may be reachable even when UFW appears to block it. Use Docker iptables false setting or publish ports carefully so your perimeter matches what you expect. Treat this as a common gotcha when hardening Ubuntu servers that also run containerised services.

No, not on a typical single-host web stack. If MySQL 8.4 or 9.7 runs on the same server, bind it to 127.0.0.1 in mysqld.cnf so it accepts local connections only. Never expose port 3306 publicly unless you have a strict IP allowlist and a clear operational reason. Add an explicit ufw deny 3306/tcp comment if you want the block documented in ufw status output during incident response.

UFW supports source IP restrictions with rules like allowing SSH only from a single office IP or a CIDR range such as a /24 subnet. Use this for admin panels, database tunnels, and deployment hooks that should not face the entire internet. For Nepal-based teams on dynamic home IPs, a bastion host or Tailscale node gives you a stable address to whitelist. Document allowed ranges in your runbook so the next admin knows why each rule exists.

Small VPS plans often run Rs 800–1,500 per month, roughly USD 6–11, while a basic VPS in Nepal typically costs Rs 1,000–3,000 per month, about USD 7–22. That price covers compute, not admin time. On a VPS from a domain and hosting provider, UFW is your responsibility, unlike shared cPanel hosts that often manage firewalls for you.

Most VPS providers including DigitalOcean, AWS Lightsail, and local Nepali hosts offer a browser-based serial console. Log in through the console, run ufw disable or ufw allow OpenSSH, then fix your rules properly before re-enabling. Some providers inject iptables rules outside UFW, so check their documentation if UFW commands seem ignored. Prevention through the two-session rule beats console recovery every time.

Share this article

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.

Quick Contact Options
Choose how you want to connect me: