October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

How to Configure a Firewall on Ubuntu with UFW

A practical Ubuntu UFW guide covering secure defaults, SSH-safe activation, service and subnet rules, rule ordering, logging, ping behavior, verification, and lockout recovery.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On Ubuntu, configure UFW by setting a default-deny inbound policy, keeping outbound traffic allowed, permitting SSH, and only then enabling the firewall:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status verbose

UFW (Uncomplicated Firewall) is disabled by default. If you enable a deny-incoming policy before allowing SSH, a remote server can immediately lock you out. Keep your existing session open, test a second connection, and verify the active rules before closing the first session.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What UFW does on Ubuntu

UFW is Ubuntu’s command-line front end for the host firewall. It writes rules for iptables, while the Linux kernel’s netfilter subsystem enforces those rules against packets entering or leaving the machine. You manage policy with readable service names, ports, addresses, and subnets instead of writing raw iptables rules.

UFW has been available by default in Ubuntu since Ubuntu 8.04 LTS (Hardy Heron). Its installed presence does not mean it is active: current Ubuntu Server documentation and the Ubuntu UFW wiki describe it as disabled initially. Enabling it is an explicit administrative step.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

The procedure below is suitable for an Ubuntu workstation or server where you want unsolicited inbound connections blocked while normal outbound connections continue. A firewall is not an application update system, malware scanner, or replacement for authentication controls; it is a network-policy layer on the host.

Before changing the firewall

Identify how you access the machine

Determine whether you are working locally at the console, through SSH, or through another remote-management service. The lockout risk is highest over SSH because enabling a default-deny policy can terminate your ability to start a new session.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Keep the current SSH window open until a second login has succeeded.
  • Confirm the SSH service name or port used by this host. The standard service is represented by OpenSSH and normally uses TCP port 22; a customized installation may use another port.
  • List the applications that must accept inbound connections, such as a web server or a private administration service. Allow only those services rather than opening a broad range of ports.

Check the current state

Run:

sudo ufw status verbose

If UFW is off, the output reports an inactive state. If it is already active, read the listed defaults and rules before adding anything. This command also displays the logging level, which is useful when diagnosing a blocked connection.

Preview a rule when you are uncertain

UFW supports a dry-run mode. For example:

sudo ufw --dry-run allow 443/tcp

The command prints the rules that would result without applying the change. Use it to check syntax or inspect a change on a production host before committing it.

Set a safe baseline policy

Block unsolicited inbound traffic

Set the incoming default to deny:

sudo ufw default deny incoming

New inbound connections that do not match an explicit allow rule are then rejected according to UFW’s policy. Existing applications should be checked individually; do not assume a service remains reachable simply because it worked before the firewall was enabled.

Permit outbound traffic

Keep the outgoing default open with:

sudo ufw default allow outgoing

This is the common server baseline: the host can initiate updates, DNS lookups, API requests, and other outbound connections, while unsolicited inbound connections require a rule. If your organization needs egress filtering, document those requirements separately and replace this default deliberately rather than adding arbitrary exceptions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Allow SSH before enabling UFW

Use the OpenSSH application profile

For a standard SSH service, add the profile rule:

sudo ufw allow OpenSSH

This must be done before sudo ufw enable. The profile maps the service name to its defined port and protocol.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Allow port 22 explicitly

If the OpenSSH profile is unavailable or you prefer an explicit rule, use:

sudo ufw allow 22/tcp

For an SSH daemon configured on another port, substitute that port, for example:

sudo ufw allow 2222/tcp

Use the actual listening port; opening port 22 does not help a daemon listening elsewhere. Restricting SSH to a management subnet can be safer than allowing it from every address:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp

The subnet example permits TCP/22 from addresses in 192.168.1.0/24. Replace it with the network you genuinely control.

Rate-limit repeated SSH attempts

UFW can rate-limit a service to slow repeated brute-force attempts:

sudo ufw limit OpenSSH

This is an additional network control, not a substitute for strong authentication, key-based access, account protection, or timely security updates.

Enable the firewall safely

Once the SSH rule and any other required management rules are in place, enable UFW:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
sudo ufw enable

Do not append a service name to the enable command. A form such as sudo ufw enable ssh is not valid UFW usage; enabling and allowing a service are separate operations.

Keep the current session open. From a second terminal or another approved host, start a fresh SSH login using the same hostname, address, port, and account. Only after that connection succeeds should you close the original session. If the second login fails, use the existing session to inspect and correct the rules.

Verify the active configuration

Read the complete status

sudo ufw status verbose

Look for an active status, the expected incoming and outgoing defaults, the SSH rule, and any application rules you intentionally added. The verbose output also identifies the logging level.

Review rules by number

sudo ufw status numbered

Numbered output makes it possible to remove a specific rule without guessing its exact textual form. Delete an unwanted entry by number:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ufw delete <number>

Replace <number> with the number shown by the status command. Re-run the numbered listing after deletion so you are working from the current order.

Add rules for the services you actually publish

Allow a named service

When a UFW application profile exists, use its name:

sudo ufw allow ssh

The same service-oriented syntax can be used for other installed profiles. Confirm the resulting entry with sudo ufw status verbose; profile names and their ports come from the host’s available application definitions.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Allow a port and protocol

Specify the protocol when the service requires it:

sudo ufw allow 53/tcp

This example permits TCP port 53 only. A UDP-based service needs its own UDP rule; do not open both protocols unless the application requires both.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Allow a trusted subnet

sudo ufw allow from 192.168.1.0/24

This permits traffic from the stated subnet. Use a narrow source range for internal administration or service-to-service traffic, and avoid treating a private address range as trustworthy unless the network is controlled and segmented appropriately.

Understand rule order

UFW evaluates rules in order. A broad allow that matches a packet can make a later, narrower deny ineffective. For example, placing an allow for an entire subnet before a deny intended to block one host means the earlier allow wins for that host.

Plan exceptions from most specific to most general. If an overly broad rule is already present, remove it with the numbered status and delete commands, then add the specific policy first and the general policy afterward. After every reordering or deletion, verify the numbered list and test from the affected source address.

Turn on logging and use it for diagnosis

Enable UFW logging with:

sudo ufw logging on

Firewall log entries are written to:

/var/log/ufw.log

When a client cannot connect, reproduce the failure, inspect the log for the source address, destination port, and action, and compare those details with the intended rule. Then check the active policy using sudo ufw status verbose. Logging records packet decisions; it does not by itself identify whether an application is listening or healthy, so pair it with the service’s own status and logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common configuration tasks

Permit a web or application port

First establish whether the application uses TCP, UDP, or both, then add only the required protocol-specific rule. Use --dry-run to inspect syntax, apply the rule, and confirm it appears in verbose status. Test from an authorized client while leaving SSH access untouched.

Limit administration to an internal network

Use a source subnet rule for the management service, such as the documented 192.168.1.0/24 pattern. Ensure your own client address belongs to that range before enabling or tightening the policy. A remote address that changes outside the permitted subnet will no longer match the rule.

Remove an obsolete exception

  1. Run sudo ufw status numbered.
  2. Identify the obsolete entry and note its number.
  3. Run sudo ufw delete <number>.
  4. Run the numbered status command again and test that the service is no longer reachable from an unauthorized source.

Ping and ICMP behavior

Ping is allowed by default under UFW. If your policy requires blocking echo requests, that is not accomplished with a normal service allow or deny command; it requires editing /etc/ufw/before.rules. Make a careful backup before editing that file, document the change, and test both the desired ICMP behavior and ordinary application traffic. A ping response alone does not prove that a TCP service is reachable, and a missing response does not prove that every protocol is blocked.

Recover from an SSH lockout

If enabling UFW prevents new SSH sessions, do not close the session that is still connected. From it, inspect:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ufw status verbose
sudo ufw status numbered

Add the correct profile, port, or source-restricted rule, then retry from a second terminal:

sudo ufw allow OpenSSH

If you use a custom port, add that port instead. If no administrative session remains, recovery requires an out-of-band console or provider recovery environment; UFW cannot be corrected through a connection that the firewall has already blocked.

Using the graphical front end

Gufw is a graphical front end intended for beginners. It exposes the same basic decisions—enable or disable UFW, set defaults, and add or remove service, port, and address rules—through a desktop interface. The safety sequence remains unchanged: allow the current SSH service first on a remote machine, enable the firewall, verify the resulting policy, and keep a second login available. The command-line status output remains a useful way to confirm exactly what the GUI applied.

Release and environment considerations

UFW syntax and the baseline procedure are stable across Ubuntu installations, but application profiles and release-specific packaging can differ. A guide targeting Ubuntu 26.04 does not establish behavior for every Ubuntu release, so verify the profile names and resulting rules on the system you are administering. The commands in this article deliberately use core UFW operations—defaults, explicit ports, status, deletion, logging, and dry-run—that can be inspected directly on the host.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cloud security groups, hypervisor firewalls, office routers, and container networking can add additional filtering layers. A connection may be blocked before it reaches UFW or may be accepted by UFW and then rejected by another layer. Test from the real client path and record which layer owns each rule so that you do not open a host firewall to compensate for a separate network policy.

A repeatable checklist

  • Confirm whether UFW is inactive or already active with sudo ufw status verbose.
  • Identify the SSH service, port, and source network used for administration.
  • Set sudo ufw default deny incoming.
  • Set sudo ufw default allow outgoing.
  • Allow SSH with sudo ufw allow OpenSSH, an explicit TCP port, or a correctly scoped subnet rule.
  • Add only the application ports and protocols that must accept inbound traffic.
  • Use sudo ufw --dry-run ... to preview uncertain changes.
  • Enable with sudo ufw enable, never by attaching a service argument.
  • Keep the first session open and verify a second SSH login.
  • Review sudo ufw status verbose and sudo ufw status numbered.
  • Enable logging when troubleshooting and inspect /var/log/ufw.log.
  • Remove broad or obsolete rules and remember that earlier matching rules take precedence.

What a correct final state looks like

A correctly configured host reports UFW as active, denies unsolicited inbound traffic by default, allows outbound traffic according to the chosen baseline, and lists an explicit SSH rule plus only the services you intend to publish. The administrator can establish a new SSH session, the numbered rule list reflects the intended order, and log entries are available when logging is enabled. That combination—not merely seeing the word “enabled”—is the practical verification that the firewall is protecting the host without cutting off required administration.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.