Ubuntu ships UFW in its default repositories, but it often stays disabled until you need to lock down SSH, open a web port, or fix a ufw: command not found error on a minimal system. You can install UFW on Ubuntu with APT when the package is missing, then use the same workflow to enable rules, allow services, and verify whether the firewall is actually active.
The commands here work on Ubuntu 26.04, 24.04, and 22.04, including server, desktop, and minimal images where UFW may not be installed yet. The same setup extends to SSH protection, service-specific rules, logging, GUFW, troubleshooting, and removal.
Install UFW on Ubuntu
Start by checking whether UFW is already present on your Ubuntu system. Standard desktop and server installs often include the package, while minimal images and some cloud builds may not. Even when UFW is already installed, the firewall usually stays inactive until you run sudo ufw enable.
ufw version
Expected output confirming UFW is installed:
ufw 0.36.2 Copyright 2008-2023 Canonical Ltd.
Ubuntu 22.04 can report ufw 0.36.1 instead. Either version output confirms the package is installed and the ufw command is available.
If you see a command not found error instead, UFW is missing from the current system. That usually means it was removed earlier or you are working on a minimal Ubuntu install.
UFW remains the reader-facing firewall tool on Ubuntu even though the lower-level iptables command uses the nft-backed alternative on current releases. Manage this ruleset through ufw unless you have a separate, tested plan for direct nftables rules.
These commands use
sudofor package-management tasks that need root privileges. If your account is not in the sudoers file yet, use the root account or follow the guide on how to add a new user to sudoers on Ubuntu.
Install the package with APT, then rerun the version check:
sudo apt update
sudo apt install ufw
After installation completes, run ufw version again to confirm UFW is ready for configuration.
Enable IPv6 Support in UFW
UFW supports IPv6 by default on modern Ubuntu installations, so normal allow and deny rules can cover both protocols. If you’re working with legacy hosts or minimal server images, verify IPv6 support by opening the UFW configuration file:
sudo nano /etc/default/ufw
Find the line that reads IPV6=no and change it to IPV6=yes. On most current Ubuntu installations, this setting is already enabled:
# Set to yes to apply rules to support IPv6 (no means only IPv6 on loopback # accepted). You will need to 'disable' and then 'enable' the firewall for # the changes to take affect. IPV6=yes
If you change this file on a system where UFW is already active, add or confirm your SSH allow rule first on remote hosts, then restart UFW. Use local console access for the restart if remote access is not confirmed:
sudo ufw disable
sudo ufw enable
Set UFW Default Policies
Default policies define how UFW handles traffic that doesn’t match any specific rule. The recommended security posture denies all incoming connections (preventing unauthorized access) while allowing all outgoing connections (permitting your applications to reach external services). Set these defaults with the following commands:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Expected output confirming the policy changes:
Default incoming policy changed to 'deny' Default outgoing policy changed to 'allow'
With these defaults in place, your server rejects all unsolicited incoming connections while allowing internal applications to communicate outward freely. You must now explicitly allow each service that needs to accept incoming traffic.
Allow SSH Connections with UFW on Ubuntu
If you manage the system remotely, allow SSH connections before enabling the firewall. Skip this section if you only use local console access, or follow the guide to install SSH on Ubuntu first.
sudo ufw allow ssh
This rule opens the default SSH port 22. If your SSH server listens on a different port, allow that port explicitly instead:
sudo ufw allow 2222/tcp
This allows incoming connections on port 2222. Replace the port number with your actual SSH port if different.
Protect SSH with UFW Rate Limiting
SSH is one of the first services bots probe on a public server, so it is worth adding a throttle before you expose it. UFW rate limiting slows repeated connection bursts from the same address, which helps cut down brute-force noise without replacing proper SSH hardening.
Use one SSH rule style for the same port. For a new IPv4 SSH ruleset, use the limit command instead of the plain allow rule above; adding both can leave the broad allow rule matching before the rate limit.
sudo ufw limit ssh
For custom SSH ports, specify the port number with the protocol:
sudo ufw limit 2222/tcp
Current UFW output also reports Skipping unsupported IPv6 'limit' rule for SSH limit rules. If the server accepts IPv6 SSH, keep a normal dual-stack SSH allow rule and pair SSH with Fail2Ban for repeated-login blocking, or test a separate IPv6-specific policy before enabling the firewall.
Enable UFW on Ubuntu
If you are connected via SSH, complete the SSH allow step above before enabling UFW. Enabling the firewall without an SSH rule will immediately disconnect your session and lock you out of the server.
Preview UFW Rules Before Activation
Before activating the firewall, preview which rules UFW will apply:
sudo ufw show added
Expected output showing your configured rules:
Added user rules (see 'ufw status' for running firewall): ufw allow 22/tcp
This verification step confirms that SSH access rules exist before you potentially lock yourself out. If the output is empty or missing your SSH rule, add it now before proceeding.
Activate UFW on Ubuntu
Once you confirm your rules are correct, enable UFW:
sudo ufw enable
UFW prompts you to confirm because enabling the firewall may disrupt existing connections:
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y Firewall is active and enabled on system startup
Enter y to confirm. UFW now enforces your rules and starts automatically on boot.
Configure Common UFW Service Rules
After enabling UFW and securing SSH access, you can allow other connections, such as HTTP, HTTPS, or FTP, using the ufw allow command followed by the service name or port number.
Common web and file-transfer services use these UFW rules:
sudo ufw allow http
sudo ufw allow https
sudo ufw allow 21/tcp
These rules allow incoming connections for HTTP on port 80, HTTPS on port 443, and FTP on port 21. If an application needs a range of consecutive ports, add that range in one rule instead of opening each port separately.
sudo ufw allow 8000:9000/tcp
This rule opens TCP ports 8000 through 9000. Port ranges are useful when a service stack needs several consecutive ports.
Allow Access from Specific IP Addresses with UFW
To restrict one service to a specific IP address, combine the from parameter with the target port and protocol:
sudo ufw allow from 203.0.113.4 to any port 22 proto tcp
This example limits SSH access to one source address. The shorter sudo ufw allow from 203.0.113.4 form grants that address access to every port, so reserve it for trusted hosts that should reach all services.
Allow Access from Subnets with UFW
To allow a subnet to reach only SSH, use CIDR notation with the port and protocol. For instance, 192.168.1.0/24 covers addresses from 192.168.1.1 through 192.168.1.254:
sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp
This limits SSH access to the specified subnet only, which is particularly useful for restricting administrative access to your local network.
Allow Connections on Specific Interfaces with UFW
For servers with multiple network interfaces, you can create rules that apply only to a specific interface. First, identify your network interfaces:
ip addr
Network interfaces are typically named eth0, eth1, enp3s2, or similar. To allow HTTP traffic only on the public-facing interface eth0:
sudo ufw allow in on eth0 to any port 80 proto tcp
Private-only services such as databases should stay on an internal interface whenever possible. This example limits MySQL traffic to eth1:
sudo ufw allow in on eth1 to any port 3306 proto tcp
Interface-specific rules provide fine-grained control over which networks can reach particular services, preventing accidental exposure of internal services to public networks.
Deny Specific Connections with UFW
Use ufw deny when you need to block a service explicitly by name or port number.
sudo ufw deny 25/tcp
This rule denies incoming SMTP connections on port 25.
For hardened hosts, UFW can also block outbound traffic. A common example is blocking direct SMTP delivery so local services cannot send mail straight to the internet:
sudo ufw deny out 25/tcp
Use outbound deny rules carefully, because they can interrupt package downloads, time synchronization, or application traffic if you block the wrong port.
Delete UFW Rules
When a rule no longer matches a running service, remove it with ufw delete and the same rule syntax you used to create it.
sudo ufw delete allow 21/tcp
This removes the rule that allows incoming connections on port 21 for FTP.
Delete UFW Rules by Number
Deleting by number is faster when the rule is long or you want to remove one entry from a crowded ruleset. Start by listing the numbered rules:
sudo ufw status numbered
The output assigns a number to each rule. Use that number when you want to remove one entry quickly:
sudo ufw delete 3
This removes the third rule from the list. Note that when deleting IPv6 rules by number, you must delete the IPv4 and IPv6 versions separately since they appear as distinct numbered entries. Deleting by name (e.g., sudo ufw delete allow http) removes both IPv4 and IPv6 rules automatically.
View UFW Status and Active Rules
After configuring your rules, check the firewall status and view active rules:
sudo ufw status verbose
The output shows the UFW status, default policies, and all configured rules. The verbose view also includes the current logging level and routed-policy state:
Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp ALLOW IN Anywhere 22/tcp (v6) ALLOW IN Anywhere (v6)
Enable and Monitor UFW Logs on Ubuntu
UFW provides logging functionality to track its actions and monitor potential issues. This section covers how to configure and view logs to maintain visibility into firewall activity.
Configure UFW Log Settings
To enable logging for UFW, use the ufw logging command followed by the desired log level. UFW supports four log levels that determine the amount of detail captured:
| Level | What It Logs |
|---|---|
| low | Blocked packets only |
| medium | Blocked packets + new connections |
| high | Packets with rate limiting |
| full | Everything without rate limiting |
For most users, medium provides a good balance between detail and log file size:
sudo ufw logging medium
The medium level logs blocked packets and new connections, providing visibility into denied traffic and established connections without overwhelming your disk with every packet detail.
View UFW Logs
UFW stores its log at /var/log/ufw.log. Open the file with less, follow new entries with the tail command in Linux, or print it with cat for quick checks.
sudo less /var/log/ufw.log
less opens the log in a scrollable view, which is useful when you want to inspect older entries without printing the entire file at once.
Manage UFW Application Profiles on Ubuntu
Some Ubuntu packages register ready-made UFW profiles, which saves you from remembering every port by hand. The available list depends on what is installed on the current system, so check your own host before you rely on a profile name.
sudo ufw app list
Relevant output includes:
Available applications: CUPS OpenSSH Wsdd
To inspect one of those profiles in detail, run ufw app info with the profile name. OpenSSH is a practical example because it maps to the same port 22 rule used in the SSH section:
sudo ufw app info OpenSSH
Relevant output includes:
Profile: OpenSSH Title: Secure shell server, an rshd replacement Description: OpenSSH is a free implementation of the Secure Shell protocol. Port: 22/tcp
Allow or deny a profile by using the exact profile name from ufw app list:
sudo ufw allow OpenSSH
Test UFW Rules on Ubuntu
Before applying new rules to production systems, preview the change and then test it from another host. That catches syntax mistakes before they reach a live firewall and gives you a real connectivity check afterward.
Preview UFW Rule Changes with --dry-run
UFW can show the rule it would generate without applying it. This is the safest way to check a new command before you change a production firewall:
sudo ufw --dry-run allow http
Relevant output includes:
### RULES ### ### tuple ### allow tcp 80 0.0.0.0/0 any 0.0.0.0/0 in -A ufw-user-input -p tcp --dport 80 -j ACCEPT ### END RULES ### Rules updated
Test Open Ports with Netcat on Ubuntu
After the dry run looks correct, test live access with nc (netcat) to confirm the port behaves the way you expect.
Install netcat if it is not already available:
sudo apt install netcat-openbsd
On the server, start a listener on port 8080:
nc -l 8080
The terminal waits for incoming connections. From a second machine or terminal session, connect to the server:
nc 192.168.1.10 8080
Replace 192.168.1.10 with your server’s actual IP address. If the connection succeeds, text you type in either terminal appears in the other, confirming the port is open through UFW. If the connection times out or is refused, UFW is blocking the traffic and you need to add an allow rule for that port.
Disable or Reset UFW on Ubuntu
You may need to temporarily disable UFW while troubleshooting a service or testing new rules. For a deeper walkthrough, see how to enable or disable the firewall on Ubuntu after the basic commands below.
sudo ufw disable
Relevant output includes:
Firewall stopped and disabled on system startup
To reset UFW to its default settings and remove all rules, use the ufw reset command. This is useful when you want to start fresh after experimenting with complex rule sets or when transitioning to a new security configuration:
sudo ufw reset
Resetting UFW erases all custom rules and returns the firewall to its default state.
Relevant output includes:
Resetting all rules to installed defaults. This may disrupt existing ssh connections. Proceed with operation (y|n)? y
UFW may also print backup paths for existing rule files under /etc/ufw/ before completing the reset.
Install GUFW on Ubuntu
GUFW adds a graphical interface on top of UFW for readers who prefer managing firewall rules from the desktop. Ubuntu publishes GUFW in the Universe repository on all supported LTS releases, so enable Universe first if apt cannot find the package. GUFW still needs an active graphical session, while the UFW CLI works the same way over SSH and on headless servers.
If you need that repository first, follow the guide to enable Universe and Multiverse in Ubuntu, then install GUFW with APT:
sudo apt update
sudo apt install gufw
Confirm that GUFW is installed before launching it from the application menu:
dpkg -s gufw | grep -E '^(Status|Version):'
Relevant output includes:
Status: install ok installed Version: 26.04.0-0ubuntu1
Ubuntu 24.04 and 22.04 show their own GUFW package version on the second line, but the Status: install ok installed line stays the same. After installation, launch GUFW from the desktop application menu; keep using the UFW CLI on headless servers and SSH-only sessions.
UFW Security Best Practices on Ubuntu
Maintaining effective firewall protection requires ongoing attention and adherence to security principles. Following these practices ensures your UFW configuration remains secure and aligned with your system’s evolving needs.
Apply Least-Privilege UFW Rules
Least privilege is the simplest way to keep a firewall honest: open only what a service truly needs, and leave everything else closed. UFW starts you in the right direction because the default incoming policy stays restrictive until you add explicit allow rules.
Be specific when creating rules. Instead of allowing broad port ranges, open only the exact ports your applications require. When a service only needs access from specific locations, restrict the rule to that source IP address or subnet. For example, to allow MySQL access only from an application server at 203.0.113.100:
sudo ufw allow from 203.0.113.100 to any port 3306 proto tcp
Audit UFW Rules Regularly
Server requirements change over time as services are added, removed, or reconfigured. Therefore, set a recurring reminder to review your firewall rules quarterly. List your rules with sudo ufw status numbered and evaluate each one:
- Is the service associated with this port still running and in use?
- Is the level of access (from anywhere vs. specific IP) still appropriate?
- Could this rule be made more restrictive without breaking functionality?
To view your numbered rules, run:
sudo ufw status numbered
A numbered ruleset looks like this:
Status: active
To Action From
-- ------ ----
[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 80/tcp ALLOW IN Anywhere
[ 3] 443/tcp ALLOW IN Anywhere
[ 4] 3306/tcp ALLOW IN 192.168.1.100
[ 5] 8080/tcp ALLOW IN Anywhere
[ 6] 22/tcp (v6) ALLOW IN Anywhere (v6)
[ 7] 80/tcp (v6) ALLOW IN Anywhere (v6)
[ 8] 443/tcp (v6) ALLOW IN Anywhere (v6)
[ 9] 8080/tcp (v6) ALLOW IN Anywhere (v6)
If you identify an outdated rule, such as port 8080 for a development server that no longer runs, remove it by number:
sudo ufw delete 5
Remember to delete both IPv4 and IPv6 versions when removing rules by number. After deleting rule 5 (8080/tcp), you would need to run sudo ufw status numbered again and delete the corresponding IPv6 rule. Alternatively, delete by service name to remove both versions simultaneously:
sudo ufw delete allow 8080/tcp
Remove unnecessary rules as soon as you confirm a service is gone. A rule that was necessary six months ago can turn into unnecessary exposure today.
Monitor UFW Logs for Suspicious Activity
Firewall logs provide valuable intelligence about traffic reaching your server, including blocked malicious attempts. Keep logging at the medium level with sudo ufw logging medium (or adjust to the level you selected earlier) and regularly review /var/log/ufw.log for patterns.
To monitor logs in real-time, use:
sudo tail -f /var/log/ufw.log
A typical blocked connection appears in the log as:
Nov 8 14:23:45 server kernel: [UFW BLOCK] IN=eth0 OUT= MAC=00:00:00:00:00:00 SRC=198.51.100.42 DST=203.0.113.10 LEN=40 TOS=0x00 PREC=0x00 TTL=52 ID=54321 PROTO=TCP SPT=54892 DPT=23 WINDOW=65535 RES=0x00 SYN URGP=0
Key log fields to monitor:
- SRC: Source IP address (who sent the packet) –
198.51.100.42in this example - DPT: Destination port (which service they tried to reach) – port
23(Telnet) in this case - PROTO: Protocol (TCP or UDP) –
TCPhere - SPT: Source port (originating port from the sender) –
54892
To check for repeated connection attempts from a specific IP address across multiple ports, use the grep command in Linux to filter the UFW log:
sudo grep "SRC=198.51.100.42" /var/log/ufw.log | grep "BLOCK" | wc -l
Dozens of attempts from one source inside a short period usually indicate automated scanning activity. Watch for single IP addresses repeatedly attempting to connect to multiple blocked ports, which indicates port scanning activity and potential attack reconnaissance.
Verify UFW IPv4 and IPv6 Coverage
Modern Ubuntu releases enable IPv6 by default, and normal UFW allow and deny rules apply to both protocols when IPV6=yes in /etc/default/ufw. Verify this setting so you do not accidentally leave IPv6 traffic outside your firewall policy.
Check your UFW IPv6 configuration:
grep IPV6 /etc/default/ufw
This should return IPV6=yes. When checking sudo ufw status verbose, look for (v6) entries corresponding to each IPv4 rule:
sudo ufw status verbose
Example output showing dual-protocol coverage:
Status: active Logging: on (medium) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp ALLOW IN Anywhere 80/tcp ALLOW IN Anywhere 443/tcp ALLOW IN Anywhere 22/tcp (v6) ALLOW IN Anywhere (v6) 80/tcp (v6) ALLOW IN Anywhere (v6) 443/tcp (v6) ALLOW IN Anywhere (v6)
Notice how each normal service rule appears twice: once for IPv4 and once with (v6) for IPv6, confirming dual-protocol coverage. Rate-limit rules are an exception, so verify SSH separately if you used ufw limit. To check whether your system actually has IPv6 connectivity, inspect your network interfaces:
ip -6 addr show scope global
If the command returns global IPv6 addresses, your system needs firewall coverage on both protocols. If your network does not use IPv6, leaving UFW IPv6 handling enabled is usually safer than assuming IPv6 can never appear later.
Integrate UFW with Fail2Ban on Ubuntu
UFW enforces a static ruleset, but it does not react to repeated login abuse on its own. Pair it with the guide to install Fail2Ban on Ubuntu to block repeated attack attempts automatically through UFW deny rules.
Troubleshoot Common UFW Issues on Ubuntu
Even well-configured firewalls encounter problems. This section covers the most common UFW issues and their solutions.
Fix sudo: ufw: command not found
Minimal Ubuntu images, cloud templates, containers, or previously cleaned systems can miss the ufw package even though standard Ubuntu installs usually include it. The error often appears as one of these messages:
sudo: ufw: command not found ufw: command not found
Check whether the binary exists in the current shell path:
command -v ufw || echo "ufw is not installed"
If the command reports that UFW is not installed, refresh APT metadata and install the package from Ubuntu’s main repository:
sudo apt update
sudo apt install ufw
Verify the command is available before continuing with firewall rules:
ufw version
Recover from UFW SSH Lockout
If you enabled UFW without allowing SSH and lost remote access, you need physical or console access to the server. Once you have console access, disable the firewall:
sudo ufw disable
Add the SSH rule and re-enable:
sudo ufw allow ssh
sudo ufw enable
Verify the rule exists before attempting to reconnect:
sudo ufw status | grep 22
Expected output:
22/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6)
UFW Fails to Start After Reboot
If UFW is inactive after a reboot, check the firewall state first. The systemd unit can show active (exited) even when UFW itself is disabled, so ufw status is the important check:
sudo ufw status
If the output says Status: inactive, confirm whether UFW is disabled in its startup configuration:
grep '^ENABLED=' /etc/ufw/ufw.conf
Relevant output when UFW has been disabled:
ENABLED=no
If the file already shows ENABLED=yes but sudo ufw status still reports inactive, reload the firewall with the same enable command after checking the staged rules.
Review your staged rules, confirm SSH access is allowed if you are remote, and enable UFW again:
sudo ufw show added
sudo ufw enable
Fix UFW Rules That Do Not Take Effect
If newly added rules do not seem to work, first confirm UFW is active:
sudo ufw status
If the status shows “inactive,” enable UFW with sudo ufw enable. Then verify that the rule syntax matches what you expect:
sudo ufw status numbered
Rule order matters. UFW checks rules from the top down, so an earlier broad deny can override the specific allow you expected to match. Remove the conflicting entry or insert the more specific rule higher in the list.
If you need a rule to take precedence immediately, insert it at the top of the ruleset instead of rebuilding every entry manually:
sudo ufw insert 1 allow 80/tcp
Relevant output includes:
Rules updated Rules updated (v6)
When you review the staged rules afterward, the new entry appears above the older SSH rule:
sudo ufw show added
Relevant output includes:
Added user rules (see 'ufw status' for running firewall): ufw allow 80/tcp ufw allow 22/tcp
Remove UFW from Ubuntu
In most cases, simply disabling UFW with sudo ufw disable is sufficient when you need to temporarily stop firewall enforcement. Complete removal is only necessary when switching to a different firewall solution like firewalld or nftables.
First, disable the firewall to prevent any disruption:
sudo ufw disable
Remove the UFW package and its configuration files:
sudo apt purge ufw
If you installed GUFW, remove it as well:
sudo apt purge gufw
Preview orphaned dependency cleanup before removing anything else:
sudo apt autoremove --dry-run
If the preview lists only packages you intentionally want to remove, run the cleanup interactively:
sudo apt autoremove
Verify UFW is no longer installed with an installed-state check, not just repository metadata:
dpkg-query -W -f='${db:Status-Abbrev} ${binary:Package}\n' ufw 2>/dev/null | grep '^ii' || echo "ufw is not installed"
Relevant output includes:
ufw is not installed
Running ufw version afterward also returns command not found unless another package or custom installation has put a different ufw command in the path.
Removing UFW leaves your system without a firewall. If you need continued protection, install an alternative firewall like iptables or nftables before removing UFW, or ensure your network has adequate perimeter security.
Conclusion
UFW is installed on Ubuntu and ready to enforce SSH, web, and custom service rules with logging and optional GUFW desktop management. For broader day-to-day control, see how to enable or disable the firewall on Ubuntu, and use the guide to install Fail2Ban on Ubuntu when you need automatic bans for repeated attacks.


Formatting tips for your comment
You can use basic HTML to format your comment. Useful tags currently allowed in published comments:
<code>command</code>command<strong>bold</strong><em>italic</em><blockquote>quote</blockquote>