For our Blog Visitor only Get Additional 3 Month Free + 10% OFF on TriAnnual Plan YSBLOG10
Grab the Deal

How to Setup UFW on Linux Server

UFW (Uncomplicated Firewall) is a simple interface to manage iptables/nftables on Linux. To set up UFW on a Linux server: install it, set default policies (deny incoming, allow outgoing), allow SSH, open required service ports (e.g., HTTP/HTTPS), enable UFW, and verify rules. This protects your server with minimal, readable commands.

If you’re looking to setup UFW on a Linux server safely and quickly, this step-by-step guide covers everything from installation to advanced rules, troubleshooting, Docker considerations, and best practices. Written from a hosting and security perspective, it helps beginners get production-grade protection with a few commands—without locking themselves out.

What Is UFW and Why Use It?

UFW (Uncomplicated Firewall) is a user-friendly command-line tool that manages Linux firewall rules. Under the hood, it configures iptables or nftables depending on your distribution. It’s included by default on Ubuntu and available for most Debian/RHEL-based systems. UFW reduces complexity with human-readable commands like “allow 22/tcp,” making it ideal for developers and sysadmins.

Key benefits:

  • Beginner-friendly syntax for secure defaults
  • Quick rule management for common services (SSH, HTTP, HTTPS)
  • Profiles for applications (OpenSSH, Apache, Nginx, Postfix)
  • IPv4 and IPv6 support
  • Persistent across reboots
  • Works well on VPS, dedicated, and cloud servers

Search Intent: Secure, Fast, and Reliable UFW Setup

Most readers want a safe, copy-paste path to enable UFW without losing SSH access, plus answers to common questions: how to allow services, open ports, block IPs, log and test rules, use IPv6, handle Docker, and recover from mistakes. This guide delivers that with a best-practice Quick Start and deep dives for production use.

Prerequisites and Safety Checklist

  • Root or sudo access on your Linux server
  • Your SSH port number (default 22; custom if you changed it)
  • Service ports you plan to allow (e.g., 80, 443, 5432)
  • Console/serial access or recovery method from your provider in case of lockout
  • For cloud servers (AWS, GCP, Azure, DigitalOcean): align security groups/VPC firewalls with UFW

On Ubuntu and Debian, UFW is often installed by default. If not, install it:

sudo apt update
sudo apt install ufw

On Fedora:

sudo dnf install ufw
# Fedora defaults to firewalld. If you choose UFW, stop/disable firewalld first:
sudo systemctl stop firewalld
sudo systemctl disable firewalld
sudo systemctl mask firewalld
sudo systemctl enable ufw
sudo systemctl start ufw

On RHEL, AlmaLinux, Rocky Linux (enable EPEL if required):

sudo dnf install epel-release -y
sudo dnf install ufw -y
sudo systemctl stop firewalld
sudo systemctl disable firewalld
sudo systemctl mask firewalld
sudo systemctl enable ufw
sudo systemctl start ufw

Important: Do not run firewalld and UFW simultaneously. Choose one firewall manager to avoid conflicts.

Quick Start: Secure Setup in 5 Minutes

Follow this safe sequence to configure UFW without losing access.

# 1) Check if IPv6 should be managed too (recommended on dual-stack servers)
sudo nano /etc/default/ufw
# Ensure: IPV6=yes
# Save and exit if you changed it:
# Then reload defaults after enabling later

# 2) Allow SSH FIRST (replace 22 if using a custom port)
sudo ufw allow 22/tcp comment 'SSH'

# 3) Set sensible defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing

# 4) Allow web traffic if this is a web server
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'

# 5) Enable UFW (type 'y' to proceed)
sudo ufw enable

# 6) Verify
sudo ufw status verbose

If you changed /etc/default/ufw for IPv6, apply and reload:

sudo ufw reload
sudo ufw status numbered

Essential UFW Commands (Cheat Sheet)

  • Enable/Disable: sudo ufw enable, sudo ufw disable
  • Status: sudo ufw status, sudo ufw status verbose, sudo ufw status numbered
  • Allow/Deny: sudo ufw allow 22/tcp, sudo ufw deny 25/tcp
  • Delete by number: sudo ufw status numbered then sudo ufw delete <num>
  • Rate limit (SSH): sudo ufw limit 22/tcp
  • Allow a range: sudo ufw allow 10000:20000/tcp
  • Allow by IP/subnet: sudo ufw allow from 203.0.113.10 to any port 22 proto tcp, sudo ufw allow from 10.0.0.0/24 to any port 5432
  • Interface-specific: sudo ufw allow in on eth0 to any port 22
  • Logging: sudo ufw logging on (levels: off, low, medium, high, full)
  • Reset: sudo ufw reset (removes rules; use carefully)

Configure Common Services

SSH (Remote Access)

Always allow your SSH port before enabling UFW. If you moved SSH to a custom port (e.g., 2222), adjust accordingly:

# Default
sudo ufw allow 22/tcp comment 'SSH'

# Custom
sudo ufw allow 2222/tcp comment 'SSH (custom port)'

# Add rate limiting to slow brute-force attempts
sudo ufw limit 22/tcp

Web Servers (Nginx/Apache)

On Ubuntu, UFW can use application profiles:

# Show available app profiles
sudo ufw app list

# Common profiles:
sudo ufw allow 'Nginx Full'        # 80,443
sudo ufw allow 'Apache Full'       # 80,443

Generic port-based rules work everywhere:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Databases (PostgreSQL, MySQL/MariaDB)

Only allow database ports from trusted hosts or private networks.

# PostgreSQL (5432) from app server only
sudo ufw allow from 10.0.0.10 to any port 5432 proto tcp

# MySQL/MariaDB (3306) from specific subnet
sudo ufw allow from 10.0.1.0/24 to any port 3306 proto tcp

Mail, FTP, and Other Services

# SMTP
sudo ufw allow 25/tcp

# SMTPS/Submission
sudo ufw allow 465/tcp
sudo ufw allow 587/tcp

# IMAP(S) and POP3(S)
sudo ufw allow 993/tcp
sudo ufw allow 995/tcp

# FTP (and passive range example)
sudo ufw allow 21/tcp
sudo ufw allow 30000:31000/tcp

For FTP passive mode, also configure your FTP server to use the same passive port range.

Advanced UFW Rules and Scenarios

Default Policies

# Recommended defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing

# For hardened egress control (optional)
sudo ufw default deny outgoing
# Then allow specific outbound destinations/ports as needed

Allow by Source, Port, Protocol

# Single IP
sudo ufw allow from 203.0.113.5 to any port 22 proto tcp

# CIDR subnet
sudo ufw allow from 10.10.0.0/16 to any port 9200 proto tcp

# UDP example (DNS)
sudo ufw allow 53/udp

Interface-Specific Rules

Helpful when your server has public and private interfaces:

# Only allow SSH on public interface eth0
sudo ufw allow in on eth0 to any port 22 proto tcp

# Allow database only on private interface eth1
sudo ufw allow in on eth1 to any port 5432 proto tcp

Port Ranges and Service Groups

# TCP range
sudo ufw allow 2000:2100/tcp

# UDP range
sudo ufw allow 60000:61000/udp

Rate Limiting and Brute-Force Mitigation

Rate limiting throttles repeated connection attempts from the same IP:

sudo ufw limit 22/tcp
sudo ufw limit 80/tcp
sudo ufw limit 443/tcp

For deeper protection, pair UFW with Fail2ban to dynamically ban abusive IPs based on log patterns.

IPv6 Support

Enable IPv6 in /etc/default/ufw (IPV6=yes) and reload. UFW will then manage ip6tables/nftables rules to match your IPv4 policy, ensuring your server isn’t exposed over IPv6 unintentionally.

NAT, Forwarding, and Port Redirection

UFW can handle NAT and forwarding by editing before.rules and default forward policy. Example: redirect port 80 to 8080 on the same server.

# 1) Enable forwarding in /etc/default/ufw
DEFAULT_FORWARD_POLICY="ACCEPT"

# 2) Edit /etc/ufw/before.rules (IPv4) and add before the *filter section:
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
COMMIT

# 3) Reload
sudo ufw reload

Be cautious: NAT changes impact traffic flow. Test carefully and document your modifications.

UFW and Docker: What You Need to Know

Docker manipulates iptables directly, which can bypass UFW’s default policy. By default, published container ports are open on the host even if UFW denies incoming. Options:

  • Bind containers to specific interfaces (e.g., 127.0.0.1) and reverse-proxy via Nginx that UFW controls.
  • Use Docker’s user-defined bridge networks and avoid --publish except through a controlled proxy.
  • Harden Docker’s iptables behavior (dockerd flags) if you know what you’re doing.

Practical approach: expose services via Nginx on 80/443, secure those ports with UFW, and keep containers on internal networks.

Testing, Verification, and Logging

Verify open ports and rules after enabling UFW:

# On the server
sudo ufw status verbose
ss -tulpn

# From a remote host
nmap -Pn <server_ip>
nc -zv <server_ip> 22
curl -I http://<server_ip>

Enable logging to capture dropped/allowed traffic:

sudo ufw logging medium
# Logs usually at /var/log/ufw.log (or via syslog/journal)
sudo tail -f /var/log/ufw.log

Troubleshooting and Recovery

Avoiding Lockouts

  • Always allow SSH (correct port) before enabling UFW.
  • Open a second SSH session before applying changes so you can revert if the first session drops.
  • Keep console/serial access ready from your hosting panel.

Common Fixes

# If you lost access (via console):
sudo ufw disable

# Re-allow SSH and re-enable:
sudo ufw allow 22/tcp
sudo ufw enable

# Reset all rules (careful: wipes configuration)
sudo ufw reset
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw enable

# Delete a bad rule by number
sudo ufw status numbered
sudo ufw delete <number>

If services are blocked by an upstream firewall (AWS Security Groups, Cloud provider firewalls), adjust those rules to match UFW. Both layers must allow the traffic.

Hardening Tips and Best Practices

  • Least privilege: Allow only required ports/IPs; deny everything else.
  • Prefer IP- or subnet-restricted rules for admin services and databases.
  • Enable IPv6 management and ensure parity between IPv4 and IPv6 rules.
  • Use rate limiting on SSH and high-risk ports; add Fail2ban for dynamic bans.
  • Segment networks: use private subnets for backend services.
  • Log at “medium” or “high” temporarily when diagnosing; revert to “low” for normal operation.
  • Document every rule with a comment so teams understand intent.
  • Review rules quarterly; remove stale allowances.

Automating UFW (Cloud-Init and Ansible)

Cloud-Init Snippet

#cloud-config
packages:
  - ufw
runcmd:
  - sed -i 's/IPV6=no/IPV6=yes/' /etc/default/ufw
  - ufw default deny incoming
  - ufw default allow outgoing
  - ufw allow 22/tcp comment 'SSH'
  - ufw allow 80/tcp comment 'HTTP'
  - ufw allow 443/tcp comment 'HTTPS'
  - yes | ufw enable
  - ufw status verbose

Ansible Task Example

- name: Install UFW
  apt:
    name: ufw
    state: present
  become: yes

- name: Configure UFW defaults
  ufw:
    state: enabled
    policy: deny
    direction: incoming
  become: yes

- name: Allow outgoing by default
  command: ufw default allow outgoing
  become: yes

- name: Allow SSH, HTTP, HTTPS
  ufw:
    rule: allow
    port: "{{ item }}"
    proto: tcp
  loop:
    - "22"
    - "80"
    - "443"
  become: yes

UFW vs. firewalld vs. iptables/nftables

  • UFW: Simple, human-readable, great for most single-host setups and Ubuntu/Debian environments.
  • firewalld: Default on RHEL/Fedora-based systems; dynamic zones and services; good for complex, multi-interface environments.
  • iptables/nftables: Low-level, most flexible; steeper learning curve; ideal for advanced scenarios and custom automation.

Choose the tool your team can manage well. Consistency and correct policy are more important than the specific framework.

Real-World Example: Production Web App

  • Web VM: allow 22/tcp from office IPs only; allow 80/443 to the world; route app traffic to containers via Nginx; deny everything else.
  • DB VM: allow 5432 only from the Web VM private subnet; no public DB access.
  • Cache VM: allow 6379 only from Web VM private subnet; no public access.
  • Monitoring: allow 9100 and 9090 from monitoring subnet only.

This follows least privilege and isolates critical services while keeping the public surface minimal.

Soft Recommendation: Secure Hosting with YouStable

As a hosting provider, YouStable offers SSD-powered VPS and dedicated servers where you can deploy UFW-ready images, leverage DDoS protection, and get guidance on firewall hardening. If you’re migrating or scaling, our team can help you set up UFW policies aligned with your stack and compliance needs.

FAQs: Setup UFW on Linux Server

Is UFW enabled by default on Ubuntu?

No. UFW is installed by default on many Ubuntu images but not always enabled. Check with sudo ufw status. If it says “inactive,” configure your rules and run sudo ufw enable.

How do I allow SSH safely before enabling UFW?

Run sudo ufw allow 22/tcp (or your custom SSH port) first, then set defaults (deny incoming, allow outgoing), then sudo ufw enable. Keep a second SSH session open to test and revert if needed.

How do I open a port with UFW?

Use sudo ufw allow <port>/<proto>. For example, open HTTP and HTTPS with sudo ufw allow 80/tcp and sudo ufw allow 443/tcp. You can also allow ranges: sudo ufw allow 10000:20000/tcp.

How do I block a specific IP with UFW?

Use a deny rule, optionally for a specific port: sudo ufw deny from 203.0.113.10 or sudo ufw deny from 203.0.113.10 to any port 22 proto tcp. Check precedence: more specific rules (by IP and port) match before broad rules.

Does UFW work with IPv6?

Yes. Set IPV6=yes in /etc/default/ufw, then reload. UFW will manage both IPv4 and IPv6 rules, keeping your policy consistent across stacks.

How do I reset or remove all UFW rules?

Run sudo ufw reset to delete all rules and restore defaults. Then reapply your policy: defaults, allow SSH, required ports, and sudo ufw enable. Be careful when running reset on remote servers.

Is UFW better than firewalld?

They solve the same problem with different approaches. UFW is simpler and common on Ubuntu/Debian. firewalld is default on RHEL/Fedora and offers zones and dynamic management. Choose the one that fits your distro and team skill set; don’t run both together.

Final Word

Setting up UFW on a Linux server is one of the fastest ways to reduce your attack surface. Use deny-by-default, allow only essential services, enable IPv6, log thoughtfully, and test thoroughly. With the quick-start steps and advanced examples above, you can move from basic protection to a hardened, production-ready firewall policy in minutes.

Alok Trivedi

Leave a Comment

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

Scroll to Top