Marcio Cunha

How to configure firewall rules with UFW on Ubuntu

Learn step by step how to configure UFW on Ubuntu to close open ports, secure your server, and safely allow backend application traffic.

Marcio Cunha•5 min
Also available in:EspañolPortuguês
Summary
  • UFW simplifies packet filtering management by wrapping iptables complexity into friendly terminal commands.
  • A default posture of denying incoming traffic and allowing outgoing traffic creates a strong initial security baseline.
  • Selectively opening ports for backend applications prevents unnecessary public exposure of internal microservices.
  • Subnet-restricted rules protect internal databases and sensitive backend APIs from unwanted external probing.
  • Regularly auditing active firewall rules and monitoring connection status helps detect unauthorized access attempts.

Why UFW is essential for securing your Ubuntu server

When you deploy a Linux server to the cloud, it instantly becomes visible to thousands of automated scans and malicious bots searching for open entry points. To prevent intrusions, we rely on a firewall, which acts like a strict security guard at your network perimeter, deciding who gets in and who stays out. On Ubuntu, the default utility for this task is UFW, short for Uncomplicated Firewall, created precisely to simplify system protection without forcing administrators to decipher complex network rules.

Before UFW, configuring security required dealing directly with iptables, a native Linux kernel utility known for its dense and cryptic syntax. In practice, this means a single misplaced comma in raw iptables could instantly drop your remote SSH connection or leave your entire machine vulnerable. UFW acts as a user-friendly wrapper over that underlying system, allowing you to secure ports and services using straightforward commands, saving time and preventing critical configuration errors.

How to install and safely enable UFW on Ubuntu

On most modern Ubuntu installations, UFW comes pre-installed, but it remains disabled by default to prevent users from locking themselves out on first boot. The vital preliminary step before enabling any blocking rules is ensuring you do not cut off your own remote access, especially when managing servers via SSH, the encrypted remote shell protocol. If you close port 22 before permitting remote access, you will lose administrative control over the machine immediately.

To verify if the utility is present and check its current status, run the following command in your terminal. If for any reason it is missing, installing it via the package manager is straightforward:

sudo apt update && sudo apt install ufw -y
sudo ufw status verbose

With the tool ready, your first mandatory rule is to allow standard remote connection traffic before turning protection on. To deepen your infrastructure risk mitigation strategy, it is worth reading the guide on how to unblock ports on Linux UFW firewall and understanding the operational impacts of these changes.

Setting default policies and allowing SSH access

Setting default policies establishes the baseline behavior of the firewall when no specific rule matches incoming or outgoing packets. The recommended security stance for backend servers is a strict deny policy for incoming traffic, meaning absolutely nothing can reach your internal services unless explicitly authorized. For outgoing traffic, allowing everything is standard practice so applications can fetch package updates and communicate with external APIs.

To apply this conceptual foundation and guarantee risk-free remote access, execute the following command sequence in your terminal:

  1. Set the default policy to deny all incoming connection attempts:
    sudo ufw default deny incoming
  2. Set the default policy to allow all outgoing requests originating from the server:
    sudo ufw default allow outgoing
  3. Explicitly allow standard remote SSH access before activating the firewall:
    sudo ufw allow 22/tcp

After executing these steps, the system is fully prepared for final activation without surprises. If your infrastructure utilizes a custom SSH port for security hardening, replace the number 22 with the exact port value defined in your SSH daemon configuration file.

Enabling the firewall and validating initial rules

With foundational rules in place, it is time to officially turn on the protection system and verify that everything operates smoothly. To activate the utility, we use the enable command, which triggers a quick confirmation prompt ensuring you are not risking your active terminal session. To handle advanced heavy traffic scenarios and connection load balancing alongside your firewall, you can also review the technical material on how to configure HAProxy load balancing for high concurrency.

Run the following commands to start the service and inspect the detailed status panel:

sudo ufw enable
sudo ufw status numbered

In the generated output, you will see numerical identifiers assigned to each rule, making future deletions or insertions much simpler. If you ever need to temporarily disable protection for deep network troubleshooting, you can run the disable command, though this should be strictly avoided in production environments exposed to the public internet.

Allowing specific traffic for backend applications

Modern backend servers typically run on dedicated ports, such as port 3000 for Node.js applications, port 8080 for Java services, or port 5432 for PostgreSQL relational databases. Leaving these ports wide open to the outside world is an open invitation for denial-of-service attacks and direct intrusion attempts against your data layers. The golden rule is to expose only the reverse proxy web server (like Nginx or Caddy) to the public and keep your backend isolated.

If you need to grant backend port access to a specific IP address belonging to your development team or a partner server, define the source explicitly in the command. Here is how to open a restricted port:

sudo ufw allow from 192.168.1.50 to any port 3000 proto tcp

This approach guarantees that only the trusted machine can reach the service on port 3000, while the rest of the internet receives absolute silence from the firewall. If the application needs public browser access, such as an open public API, you open the port globally while continuously evaluating the risks of exposing sensitive payloads. To explore these architectural concepts further in production, see our related technical analysis on How to test a shorted USB-C connector with multimeter.

Conclusion and best practices for ongoing UFW management

Configuring firewall rules with UFW on Ubuntu is one of the most critical steps in transforming a raw server into a secure, resilient production environment. By closing all unnecessary ports by default and permitting only what is strictly required for your backend to function, you drastically shrink the attack surface exploitable by malicious actors. Maintaining this audit habit and periodically reviewing active rules guarantees your infrastructure integrity over the long haul.

Keep in mind that information security is not a one-time event, but rather a continuous process of monitoring and adjustment. Whenever you deploy new microservices or alter your application topology, take a moment to reassess which ports truly require external exposure. With a firm grasp of UFW and complementary network utilities, your Linux environment will be well-prepared to operate with stability and confidence.