Marcio Cunha

How to configure UFW firewall rules on Ubuntu Linux

Learn step by step how to set up UFW on Ubuntu to close unnecessary ports and securely manage your network infrastructure.

Marcio Cunha•5 min
Also available in:PortuguêsEspañol
Summary
  • UFW simplifies complex iptables packet filtering rules in Linux through intuitive textual commands
  • The default policy of blocking incoming traffic and allowing outgoing traffic protects servers from intrusions
  • Opening specific ports requires careful planning to expose only essential services to the external network
  • Controlling access by IP addresses and subnets restricts network traffic to trusted and verifiable origins
  • Validating the current status and auditing firewall logs prevents silent security flaws in production

Why UFW is essential for Ubuntu server security

Managing network security on a Linux server can feel overwhelming when dealing with raw iptables rules, the traditional packet filtering tool of the kernel. In practice, UFW, which stands for Uncomplicated Firewall, was created precisely to simplify this process, acting as a friendly interface that translates simple commands into robust network rules. Before exposing any machine to the public internet, infrastructure engineers must ensure that unnecessary ports are tightly closed, drastically reducing the attack surface against intrusions and automated port scanners.

In production environments or even home servers, maintaining a restrictive policy prevents background services from remaining vulnerable to remote exploits. When combining UFW with sound administration practices, such as regularly cleaning package caches to free disk space, you ensure an environment that is not only secure but also lean and high-performing. UFW operates by default by blocking all incoming traffic and allowing all outgoing traffic, a foundational premise ensuring the server can fetch updates while intruders cannot knock uninvited.

Installation and initial status verification

Before applying any changes to network rules, the first step is to verify whether the package is present on the operating system and check its current operational state. Although UFW comes pre-installed on most Debian and Ubuntu distributions, it is worth confirming the installation and ensuring the service is properly integrated with systemd, much like when we need to restart stuck Linux services to recover applications. To check the current status, we use direct terminal commands with administrative privileges.

Below is the initial procedure to check and prepare the firewall:

  1. Update the system package list if necessary using sudo apt update.
  2. Install the firewall package by executing the installation command.
  3. Check the current status of the service to see if it is active or inactive.
sudo apt update
sudo apt install ufw -y
sudo ufw status verbose

In practice, if the command returns an inactive status, it means all machine ports are wide open and exposed according to currently running services. Enabling UFW without first configuring essential remote access rules, such as the SSH port, can instantly lock you out of the server. Therefore, planning basic rules must always precede the final activation of the protection system.

Setting default policies and allowing essential services

The first and most important decision when configuring UFW is establishing default behavior rules for packets entering and leaving the machine. The policy recommended by any network engineer is to deny all incoming traffic and allow all outgoing traffic, ensuring the server decides who enters while internal apps retain freedom to fetch external dependencies. To deepen traffic isolation, administrators also manage local traffic using advanced networking concepts, such as unblocking specific ports in the Linux firewall for restricted communication needs.

Let us apply default policies and allow essential remote SSH access before permanently enabling the firewall:

  1. Set the default policy to deny all incoming traffic.
  2. Set the default policy to allow all outgoing traffic.
  3. Allow the default remote SSH access port to prevent session lockout.
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh

With these three instructions executed, your Ubuntu machine's security foundation is established. Terminal access will continue working seamlessly, but any connection attempts on arbitrary ports will be summarily dropped by the kernel. It is worth noting that the allow ssh rule opens port 22 by default; if your infrastructure uses a custom port to deter automated brute-force attacks, you must specify the exact port number instead of the word ssh.

Managing specific ports and restricting IP addresses

Often, opening a port to the entire world is an unnecessary security risk, especially when the service should only be accessed by an internal network, a corporate VPN, or a specific management IP address. UFW allows highly targeted rules by combining port numbers, transport protocols like TCP or UDP, and specific sources. In practice, this means you can authorize a database or admin panel to accept connections exclusively coming from the administrator's workstation or another trusted cluster server.

To illustrate creating granular rules, here is how to open HTTP traffic and restrict a database port:

  1. Open the default web port for HTTP traffic from any internet source.
  2. Authorize access to the PostgreSQL database port only for a specific IP address.
  3. Effectively enable the firewall after validating all configured rules.
sudo ufw allow 80/tcp
sudo ufw allow from 192.168.1.100 to any port 5432 proto tcp
sudo ufw enable

Upon executing the enable command, UFW enters immediate operation and starts enforcing rules in real time. If you make a mistake and lose connection, restarting the physical machine or using the cloud provider control panel will be necessary to regain access. Therefore, prior validation with the verbose command and ensuring the SSH key is allowed saves administrators from major headaches in remote environments.

Auditing and troubleshooting firewall rules in daily operations is vital. Over time, new services are installed, old ports are abandoned, and obsolete rules accumulate, causing confusion and potential security gaps. Knowing how to list numbered rules lets administrators remove incorrect entries with surgical precision by referencing the exact rule index.

To audit and clean up old system rules, use these terminal commands:

  1. List all active rules displaying their respective index numbers.
  2. Remove a specific rule using its corresponding list number.
  3. Temporarily disable the firewall if you need to perform complex network tests.
sudo ufw status numbered
sudo ufw delete 3
sudo ufw disable

Maintaining the habit of inspecting firewall status ensures that accidental changes made by third-party software installation scripts are caught early. UFW records suspicious events in system logs, allowing monitoring tools to spot attack patterns before they compromise hosted data integrity.

Final thoughts on network security best practices

The conscious and disciplined use of UFW turns Ubuntu Linux into a digital fortress ready to face internet-connected environment challenges. By closing unnecessary ports, enforcing restrictive incoming policies, and regularly auditing active rules, infrastructure engineers drastically reduce the risk of intrusions and data leaks. The simplicity of the tool should not mask its power; every rule added represents a deliberate decision about the information flow your application tolerates. Integrating this security routine into daily operations guarantees stability, predictability, and peace of mind for critical production workloads.