October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Configure a Firewall on Ubuntu with UFW

A complete Ubuntu UFW setup guide covering safe defaults, SSH protection, game-server ports, rule order, logging, verification and recovery.
Length9 min Posted Quest giverVGSources Team

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.

Use UFW (Uncomplicated Firewall) to apply a deny-by-default policy to incoming traffic while keeping outbound connections allowed. Set the defaults, allow SSH before turning the firewall on, enable it, and verify the result:

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

Do not enable a default-deny policy until the SSH rule is in place. Otherwise, a remote Ubuntu server can lock you out.

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 simpler command-line front end for firewall management. It writes rules for iptables, while the Linux kernel’s netfilter system enforces those rules. You normally work with readable service names, ports and network ranges instead of hand-writing iptables rules.

Ubuntu has included UFW since Ubuntu 8.04 LTS (Hardy Heron). Ubuntu’s current server documentation and the main UFW documentation describe it as disabled by default, so installing Ubuntu does not automatically mean that filtering is active. You must enable it deliberately after deciding which incoming services the machine needs.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

For a game server, that usually means allowing administration first, then opening only the documented listening ports for the game or other services you intentionally expose. UFW does not discover a game’s ports for you; obtain those values from the game’s own server documentation and create rules for the required protocol.

Before you change the firewall

Identify how you administer the machine

Determine whether you are connected over SSH, using a local terminal, or working through a hosting provider’s console. If the machine is remote, keep the current SSH session open while changing UFW. A second login window gives you a safe test path before you close the first session.

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

Confirm the SSH port

If the SSH daemon uses the standard port, you can allow the named service with sudo ufw allow OpenSSH or explicitly allow TCP port 22 with sudo ufw allow 22/tcp. If SSH listens on a custom port, allow that port instead:

sudo ufw allow <SSH_PORT>/tcp

Replace <SSH_PORT> with the actual configured port. Allowing port 22 when the daemon listens elsewhere will not preserve access.

Check the current state

Run:

sudo ufw status verbose

On a fresh installation, the output normally reports that the firewall is inactive. The verbose form also displays the logging level, default policies and existing rules, which gives you a baseline before making changes.

The safe activation procedure

1. Set the incoming default to deny

sudo ufw default deny incoming

This makes unsolicited incoming connections the exception rather than the norm. Services remain reachable only when you add an allow rule for them.

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

2. Keep outgoing traffic allowed

sudo ufw default allow outgoing

This permits the server to initiate outbound connections, such as package downloads, DNS lookups and connections made by game-server processes. If your environment requires outbound filtering, design that policy separately instead of assuming that an incoming rule controls it.

3. Allow SSH before enabling UFW

sudo ufw allow OpenSSH

Use the explicit form when you prefer to document the port:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
sudo ufw allow 22/tcp

For a custom SSH port, use the port on which your daemon actually listens. Keep the existing remote session open and prepare a second SSH connection from another terminal.

4. Enable the firewall

sudo ufw enable

UFW’s enable command takes no service argument. A command such as sudo ufw enable ssh is not valid usage. The SSH permission must be created with allow before you run enable.

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

5. Test a second login and inspect the result

From the second terminal, establish a new SSH connection. If it succeeds, inspect the active policy:

sudo ufw status verbose

The output should show that UFW is active, display the default incoming and outgoing policies, show the logging state and list the rules you created. Only after this check should you close the original session.

Opening ports and services

Use a service name when one exists

A service rule is easy to read and follows the service definition known to UFW:

sudo ufw allow ssh

OpenSSH and ssh are commonly used service names for SSH. If a name is not recognized or you need to be explicit, specify the port and protocol.

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

Specify a port and protocol

sudo ufw allow 53/tcp

This example allows TCP traffic to port 53. TCP and UDP are separate protocols; allowing one does not automatically allow the other. For a game server, create rules for every protocol and port the server documentation requires, and do not open additional ranges merely for convenience.

Restrict access to a private subnet

sudo ufw allow from 192.168.1.0/24

This permits traffic originating in the stated subnet. Subnet restrictions are useful for administration or a private LAN service, but they are not a substitute for authentication. Verify that the address range matches the clients that should connect.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Use rate limiting for SSH

sudo ufw limit OpenSSH

The limit action rate-limits SSH connections to slow repeated login attempts. It is intended to reduce the effect of brute-force bursts; it does not replace strong credentials, key-based authentication or account protection.

Rule order and why it matters

UFW evaluates rules in order. A broad allow rule can match a packet before a later, more specific deny is reached. In that situation, adding the deny at the end does not block the traffic you intended to stop.

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

Put narrow exceptions before broad permissions

Plan rules from most specific to most general. If you need a restricted source network and also have a broad service rule, place the restricted rule first. Review the resulting order with:

sudo ufw status numbered

The numbered listing is the authoritative view of the order UFW will use. If a rule is in the wrong position, remove it and add the intended rules again in the correct sequence.

Delete by rule number

sudo ufw delete <number>

Replace <number> with the index shown by sudo ufw status numbered. Recheck the list after deletion because the remaining rules may receive new numbers.

Preview a change

Use UFW’s dry-run option to print the rules that a command would produce without applying the change:

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 --dry-run allow 53/tcp

Dry runs are useful when you are editing a production game host or remote machine and want to inspect the generated result before committing it.

Opening a game server safely

Start with administration, not the game port

Allow and test SSH first. This gives you a recovery channel while you configure the service that players will use. Do not close the working SSH session until a second login has succeeded after UFW is active.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Open only documented listening ports

Find the game server’s configured listening ports and protocols in its official server documentation or configuration. Add one UFW rule per required combination. If the service uses both TCP and UDP, create separate rules or use the syntax appropriate to each protocol; a TCP rule does not cover UDP.

Check from the client side

After adding the game rules, connect from an intended client network. A successful UFW status check proves that the rules are loaded, not that the game process is listening or that upstream network controls permit the connection. If a connection fails, verify the game process, its bind address, the port and protocol, and any provider-level firewall before changing UFW blindly.

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

Keep private services private

For a LAN-only game or administration service, use a source subnet rule rather than exposing the port to every address. Test from both an allowed client and a disallowed network so that the restriction is demonstrated rather than assumed.

Verifying and auditing the active policy

Read the verbose status

sudo ufw status verbose

Look for four things: an active status, the expected logging level, the intended default policies and every required allow or limit rule. Run this command after enabling UFW and whenever you make a significant change.

Review numbered rules before editing

sudo ufw status numbered

Numbered output lets you identify duplicate, overly broad or incorrectly ordered entries. Record the list before deleting anything, then verify it again afterward.

Use logs when a connection behaves unexpectedly

sudo ufw logging on

With logging enabled, UFW writes firewall log entries to /var/log/ufw.log. Use the log to correlate blocked traffic with the source address, destination port and time of a failed connection. Logging can produce substantial output on a busy public server, so enable it with a plan to review and manage the resulting file.

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 mistakes and recovery paths

Enabling before allowing SSH

Symptom: an existing SSH connection works until it drops, and new logins fail. If you have local or provider-console access, disable UFW temporarily:

sudo ufw disable

Then add the correct SSH rule, verify it, and enable UFW again. If no out-of-band access exists, you must use the hosting provider’s recovery procedure; do not rely on the disconnected SSH session.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Allowing the wrong port

Symptom: UFW is active and the rule appears in status, but SSH or the game service is unreachable. Confirm the daemon’s actual listening port and protocol. A rule for TCP 22 cannot permit a daemon listening on a custom port, and a TCP rule cannot permit a UDP-only service.

Adding a deny after a broad allow

Symptom: a deny rule appears in the list but matching traffic still succeeds. Inspect numbered order. Remove and recreate the rules so that the specific restriction is evaluated before the broad allow.

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

Assuming UFW is the only firewall

Symptom: the local rule looks correct, yet outside clients cannot connect. UFW controls the Ubuntu host; cloud security groups, router ACLs, provider firewalls and NAT can still block or redirect traffic. Test each layer and confirm that the service is listening on the expected interface.

Ping and the before rules

Ubuntu permits ping by default under UFW. If you need to block ICMP echo requests, that behavior is controlled in /etc/ufw/before.rules rather than through a normal service allow command.

Editing that file changes rules that are loaded before ordinary UFW rules. Make a backup, change only the relevant ICMP handling, and test from a console or a second administrative path before ending your current session. A syntax mistake in the before rules can affect more than ping, so treat the file as a low-level firewall configuration rather than a routine port list.

Maintenance workflow

Document why every rule exists

Use service names where they are clear and port/protocol notation where it is more precise. Keep a short record of the game, administration service or private subnet each rule supports. This prevents old test rules from becoming permanent exposure.

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

Review after service changes

When you move SSH to another port, replace the old rule only after the new connection has been tested. When a game server changes its listening configuration, update UFW to match and remove ports that are no longer used.

Recheck after upgrades or automation

Run sudo ufw status verbose after operating-system upgrades, provisioning changes or firewall-management automation. Confirm that UFW remains active and that defaults and rule order still match the intended policy.

Use the GUI when command-line work is a barrier

Gufw is a graphical front end recommended for beginners. It represents the same basic operations—activation, default policies, service or port rules and status—through a desktop interface. Whether you use Gufw or the terminal, verify the resulting policy with UFW’s status commands and preserve an SSH recovery path on remote systems.

How UFW fits into Ubuntu’s networking stack

UFW is not a separate packet-filtering engine. It generates iptables rules, and netfilter in the Linux kernel applies those rules to packets. This layered design explains why a correct UFW rule can still be affected by another firewall layer, a service that is not listening, or a network device outside the Ubuntu host.

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

Because UFW is a policy front end, its readable commands are safer for routine administration than editing generated iptables rules directly. Use the UFW interface for normal changes and reserve low-level files such as /etc/ufw/before.rules for cases that specifically require them.

Command reference

Purpose Command
Set incoming default sudo ufw default deny incoming
Set outgoing default sudo ufw default allow outgoing
Allow named SSH service sudo ufw allow OpenSSH
Allow SSH on TCP 22 sudo ufw allow 22/tcp
Allow a TCP service port sudo ufw allow 53/tcp
Allow a source subnet sudo ufw allow from 192.168.1.0/24
Rate-limit SSH sudo ufw limit OpenSSH
Enable UFW sudo ufw enable
Disable UFW for recovery sudo ufw disable
Show active policy sudo ufw status verbose
Show numbered rules sudo ufw status numbered
Delete a numbered rule sudo ufw delete <number>
Preview a change sudo ufw --dry-run allow 53/tcp
Enable logging sudo ufw logging on

A practical checklist

  • Confirm whether you have local or console access before changing a remote host.
  • Identify the SSH port and protocol actually in use.
  • Set deny incoming and allow outgoing.
  • Allow SSH before enabling UFW.
  • Keep the first SSH session open and test a second login.
  • Enable UFW with sudo ufw enable, without appending a service name.
  • Add only the game-server ports and protocols that the service requires.
  • Use subnet rules for services intended only for a private network.
  • Check rule order with sudo ufw status numbered.
  • Use verbose status and, when needed, /var/log/ufw.log to diagnose behavior.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.