How to Secure Ubuntu Server with UFW Firewall 2026
When you need to secure Ubuntu server with UFW firewall protection becomes essential. This comprehensive guide shows you exactly how to secure Ubuntu server with UFW (Uncomplicated Firewall), Ubuntu’s user-friendly firewall management tool that provides robust security without complex configuration.
Why Secure Ubuntu Server with UFW?
Every internet-connected server faces constant security threats. Network scanning, brute-force attacks, and unauthorized access attempts happen continuously. When you secure Ubuntu server with UFW you create a critical defense layer:
- Simple Management: UFW simplifies iptables complexity with intuitive commands
- Default Deny: Block all incoming traffic by default, allow only necessary services
- Application Integration: Manage rules by application profiles instead of port numbers
- Logging Capability: Track connection attempts for security auditing
- IPv6 Support: Protect both IPv4 and IPv6 traffic automatically
- Low Overhead: Minimal resource impact on server performance
According to SANS Institute security guidelines, firewall implementation is fundamental to defense-in-depth security strategies for all internet-facing servers.
Understanding UFW Basics
Before you secure Ubuntu server with UFW understanding its architecture helps. UFW is a frontend for iptables, Linux’s powerful but complex firewall system. UFW simplifies common firewall tasks while maintaining iptables’ power.
How UFW Works
When you secure Ubuntu server with UFW it operates at the network layer, examining every incoming and outgoing packet against configured rules. UFW evaluates rules sequentially:
- Packet arrives at network interface
- UFW checks packet against rules in order
- First matching rule determines action (allow, deny, reject)
- If no rules match, default policy applies
- Allowed packets proceed to destination service
- Denied/rejected packets are dropped
UFW Default Policies
When you first secure Ubuntu server with UFW default policies follow security best practices:
- Incoming: Deny (block all incoming connections unless explicitly allowed)
- Outgoing: Allow (permit all outgoing connections from server)
- Routed: Deny (block forwarding unless server acts as router)
This “default deny” approach minimizes attack surface while maintaining server functionality.
Installing and Enabling UFW
Most Ubuntu installations include UFW by default. To secure Ubuntu server with UFW first verify installation:
Check UFW Installation
1
2 sudo ufw version
# Output: ufw 0.36.1
If UFW is missing, install it:
1
2 sudo apt update
sudo apt install ufw
Configure Default Policies
CRITICAL: Before enabling UFW, configure SSH access to prevent lockout. To secure Ubuntu server with UFW safely, always allow SSH first:
1
2
3
4
5
6
7
8 # Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (port 22)
sudo ufw allow ssh
# Or with explicit port number:
sudo ufw allow 22/tcp
Enable UFW
After allowing SSH, enable the firewall:
1 sudo ufw enable
You’ll see a warning about disrupting existing SSH connections. Type
1 | y |
to proceed. Your current SSH session remains active.
Verify UFW status:
1 sudo ufw status verbose
Output shows:
1
2
3
4
5
6
7
8
9 Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp ALLOW IN Anywhere
22/tcp (v6) ALLOW IN Anywhere (v6)
Essential UFW Rules to Secure Ubuntu Server
When you secure Ubuntu server with UFW configure rules for services your server provides.
Allow Web Server Traffic
For web servers running HTTP/HTTPS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 # Allow HTTP (port 80)
sudo ufw allow http
# Or:
sudo ufw allow 80/tcp
# Allow HTTPS (port 443)
sudo ufw allow https
# Or:
sudo ufw allow 443/tcp
# Allow both simultaneously
sudo ufw allow 'Nginx Full'
# Or for Apache:
sudo ufw allow 'Apache Full'
Allow Database Connections
For database servers, restrict access to specific IPs when you secure Ubuntu server with UFW:
1
2
3
4
5
6
7
8 # Allow MySQL from specific IP
sudo ufw allow from 192.168.1.100 to any port 3306
# Allow PostgreSQL from subnet
sudo ufw allow from 192.168.1.0/24 to any port 5432
# Allow MongoDB from specific server
sudo ufw allow from 203.0.113.50 to any port 27017
Allow Email Server Ports
For mail servers:
1
2
3
4
5
6
7
8
9
10
11
12
13 # SMTP (outgoing mail)
sudo ufw allow 25/tcp
# SMTP submission (authenticated)
sudo ufw allow 587/tcp
# IMAP (email retrieval)
sudo ufw allow 143/tcp
sudo ufw allow 993/tcp # IMAP over SSL
# POP3 (email retrieval)
sudo ufw allow 110/tcp
sudo ufw allow 995/tcp # POP3 over SSL
Allow FTP/SFTP
1
2
3
4
5
6
7
8
9 # SFTP (recommended - uses SSH)
# Already allowed if SSH is allowed
# FTP (not recommended - insecure)
sudo ufw allow 20/tcp
sudo ufw allow 21/tcp
# FTP passive mode range
sudo ufw allow 40000:50000/tcp
Allow DNS
For DNS servers:
1
2 sudo ufw allow 53/tcp
sudo ufw allow 53/udp
Advanced UFW Rules
To truly secure Ubuntu server with UFW master these advanced techniques:
Port Range Rules
Allow multiple consecutive ports:
1
2
3
4
5 # Allow port range
sudo ufw allow 6000:6007/tcp
# Allow from specific IP to port range
sudo ufw allow from 192.168.1.50 to any port 8000:8100 proto tcp
IP Address and Subnet Rules
Restrict access by source IP when you secure Ubuntu server with UFW:
1
2
3
4
5
6
7
8
9
10
11 # Allow all traffic from specific IP
sudo ufw allow from 192.168.1.100
# Allow from subnet
sudo ufw allow from 10.0.0.0/8
# Allow from IP to specific port
sudo ufw allow from 203.0.113.50 to any port 22
# Allow from subnet to specific interface
sudo ufw allow in on eth1 from 192.168.1.0/24
Network Interface Rules
Control traffic on specific interfaces:
1
2
3
4
5
6
7
8 # Allow on specific interface
sudo ufw allow in on eth0 to any port 80
# Deny on specific interface
sudo ufw deny in on eth1 to any port 3306
# Allow between interfaces (routing)
sudo ufw route allow in on eth0 out on eth1
Application Profiles
Use predefined application profiles to secure Ubuntu server with UFW efficiently:
1
2
3
4
5
6
7
8
9 # List available profiles
sudo ufw app list
# Show profile details
sudo ufw app info 'Nginx Full'
# Allow profile
sudo ufw allow 'OpenSSH'
sudo ufw allow 'Nginx HTTPS'
Common profiles include:
-
1OpenSSH
– SSH (port 22)
-
1Nginx Full
– HTTP + HTTPS (80, 443)
-
1Nginx HTTP
– HTTP only (80)
-
1Nginx HTTPS
– HTTPS only (443)
-
1Apache Full
– HTTP + HTTPS
-
1Bind9
– DNS server
-
1Dovecot IMAP
– IMAP email
Creating Custom Application Profiles
Define custom profiles for your applications:
1 sudo nano /etc/ufw/applications.d/myapp
Add profile definition:
1
2
3
4 [MyApp]
title=My Application
description=Custom web application
ports=8080,8443/tcp
Reload and use:
1
2 sudo ufw app update MyApp
sudo ufw allow MyApp
Deny and Reject Rules
Block specific traffic when you secure Ubuntu server with UFW:
1
2
3
4
5
6
7
8 # Deny connection (silently drop packets)
sudo ufw deny from 203.0.113.100
# Reject connection (send error response)
sudo ufw reject from 198.51.100.50 to any port 80
# Deny specific port
sudo ufw deny 23/tcp # Block telnet
Deny vs Reject:
- Deny: Silently drops packets, attacker sees timeout
- Reject: Sends ICMP error, attacker knows port is filtered
- Use deny for stealth, reject for legitimate traffic you want to refuse quickly
Managing UFW Rules
To secure Ubuntu server with UFW ongoing management is essential.
List All Rules
1
2
3
4
5
6
7
8 # Brief status
sudo ufw status
# Detailed status
sudo ufw status verbose
# Numbered rules (useful for deletion)
sudo ufw status numbered
Delete Rules
Remove rules by number or specification:
1
2
3
4
5
6 # Delete by number (get number from status numbered)
sudo ufw delete 3
# Delete by rule specification
sudo ufw delete allow 80/tcp
sudo ufw delete allow from 192.168.1.100
Insert Rules at Specific Position
Insert rules before others (UFW processes rules sequentially):
1
2
3
4
5 # Insert at position 1 (processed first)
sudo ufw insert 1 deny from 203.0.113.100
# Insert specific rule
sudo ufw insert 2 allow from 192.168.1.50 to any port 22
Reset UFW
Remove all rules and disable firewall:
1 sudo ufw reset
Use with caution – you’ll need to reconfigure all rules.
UFW Logging and Monitoring
When you secure Ubuntu server with UFW monitoring ensures you detect attacks and troubleshoot issues.
Enable Logging
1
2
3
4
5
6
7
8 # Enable logging (low level)
sudo ufw logging on
# Set logging level
sudo ufw logging low # Basic logging
sudo ufw logging medium # More detail
sudo ufw logging high # Verbose logging
sudo ufw logging full # Maximum detail
Logging levels:
- Off: No logging
- Low: Log blocked packets, rate-limited
- Medium: Log blocked, allowed, and invalid packets, rate-limited
- High: Log all packets without rate limiting (can generate large logs)
- Full: High + logging before/after connection tracking
View UFW Logs
UFW logs to syslog:
1
2
3
4
5
6
7
8
9
10
11 # View recent UFW logs
sudo tail -f /var/log/ufw.log
# On systemd systems:
sudo journalctl -u ufw -f
# Search for specific IP
sudo grep "192.168.1.100" /var/log/ufw.log
# Count blocked connections
sudo grep "\[UFW BLOCK\]" /var/log/ufw.log | wc -l
Analyzing UFW Logs
Log entries show:
1 Mar 18 07:30:15 server kernel: [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=203.0.113.100 DST=192.168.1.50 LEN=60 TOS=0x00 PREC=0x00 TTL=50 ID=12345 DF PROTO=TCP SPT=54321 DPT=22 WINDOW=29200 RES=0x00 SYN URGP=0
Key fields:
- SRC: Source IP address
- DST: Destination IP (your server)
- PROTO: Protocol (TCP, UDP, ICMP)
- SPT: Source port
- DPT: Destination port
- SYN: TCP connection attempt
Security Best Practices
Follow these guidelines when you secure Ubuntu server with UFW:
1. Principle of Least Privilege: Only allow absolutely necessary ports and IPs:
1
2
3
4
5 # Bad: Open to all
sudo ufw allow 3306
# Good: Restrict to specific IP
sudo ufw allow from 192.168.1.100 to any port 3306
2. Change Default SSH Port: Reduce automated attacks by moving SSH from port 22:
1
2
3
4
5
6
7
8
9 # Edit SSH config
sudo nano /etc/ssh/sshd_config
# Change: Port 2222
sudo systemctl restart ssh
# Update UFW
sudo ufw delete allow 22/tcp
sudo ufw allow 2222/tcp
3. Rate Limit SSH: Prevent brute-force attacks when you secure Ubuntu server with UFW:
1
2 sudo ufw limit ssh
# Denies connections if IP attempts 6+ connections within 30 seconds
4. Block Common Attack Ports:
1
2
3
4
5
6
7
8
9 # Block telnet (insecure)
sudo ufw deny 23/tcp
# Block SMB (often exploited)
sudo ufw deny 445/tcp
sudo ufw deny 139/tcp
# Block RDP unless needed
sudo ufw deny 3389/tcp
5. Regular Rule Audits: Review rules quarterly:
1
2
3 sudo ufw status numbered
# Remove unnecessary rules
# Tighten overly permissive rules
6. Combine with Fail2Ban: Add intrusion prevention when you secure Ubuntu server with UFW:
1
2 sudo apt install fail2ban
# Fail2Ban automatically adds UFW rules to block repeat attackers
7. Enable IPv6 Protection: Ensure UFW protects both protocols:
1
2
3
4 sudo nano /etc/default/ufw
# Set: IPV6=yes
sudo ufw reload
8. Document Your Rules: Maintain a documented firewall policy:
1
2 # Create documentation
sudo ufw status numbered > /root/ufw-rules-$(date +%Y-%m-%d).txt
The Ubuntu UFW documentation provides additional hardening recommendations.
Common UFW Scenarios
Practical examples for different server roles when you secure Ubuntu server with UFW:
Web Server Configuration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 # Reset to clean slate
sudo ufw --force reset
# Set defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (rate limited)
sudo ufw limit 22/tcp
# Allow web traffic
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Enable firewall
sudo ufw enable
Database Server Configuration
1
2
3
4
5
6
7
8
9
10
11
12
13 # Set defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH from admin subnet
sudo ufw allow from 192.168.1.0/24 to any port 22
# Allow MySQL only from application servers
sudo ufw allow from 10.0.1.10 to any port 3306
sudo ufw allow from 10.0.1.11 to any port 3306
# Enable firewall
sudo ufw enable
Development Server Configuration
1
2
3
4
5
6
7
8
9
10
11 # Allow SSH
sudo ufw allow 22/tcp
# Allow common development ports
sudo ufw allow 3000/tcp # Node.js
sudo ufw allow 8000/tcp # Django
sudo ufw allow 8080/tcp # Alternative HTTP
sudo ufw allow 5432/tcp # PostgreSQL
# Enable firewall
sudo ufw enable
Troubleshooting UFW Issues
When you secure Ubuntu server with UFW problems may occur. Here’s how to resolve them:
Problem: Locked Out After Enabling UFW
Prevention: Always allow SSH before enabling UFW.
Solution (requires console access):
1
2
3 # Access server console (VPS control panel, KVM, physical access)
sudo ufw allow 22/tcp
sudo ufw reload
Problem: Service Not Accessible Despite UFW Rule
Check rule is correctly configured:
1
2 sudo ufw status numbered
# Verify rule exists and matches expected traffic
Check service is running:
1
2 sudo systemctl status nginx
sudo netstat -tlnp | grep :80
Check rule order (first match wins):
1
2
3 # If deny rule appears before allow rule, traffic is blocked
sudo ufw status numbered
# Reorder with delete and insert
Problem: UFW Not Starting at Boot
1
2
3
4
5 # Enable UFW service
sudo systemctl enable ufw
# Verify
sudo systemctl is-enabled ufw
Problem: IPv6 Traffic Not Filtered
1
2
3
4
5 # Enable IPv6 in UFW
sudo nano /etc/default/ufw
# Set: IPV6=yes
sudo ufw reload
Problem: Too Many Log Entries
Reduce logging level:
1
2
3
4
5
6 # Change from high/full to low/medium
sudo ufw logging medium
# Or disable for specific traffic
sudo ufw delete allow from 192.168.1.0/24
sudo ufw allow from 192.168.1.0/24 comment 'Internal LAN - no log'
UFW vs iptables
Understanding when to secure Ubuntu server with UFW versus raw iptables:
Use UFW when:
- Implementing standard firewall policies
- You want simple, maintainable configuration
- Managing firewall for single server
- Team members have varying Linux expertise
Use iptables directly when:
- Complex NAT configurations required
- Advanced packet manipulation needed
- Building custom routing/forwarding rules
- Maximum performance critical (UFW adds minimal overhead but direct iptables is slightly faster)
Note: UFW and iptables can coexist, but manual iptables changes can interfere with UFW rules. Choose one approach for consistency.
Automating UFW Configuration
When you secure Ubuntu server with UFW automation ensures consistency across multiple servers:
UFW Configuration Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 #!/bin/bash
# ufw-setup.sh - Automated UFW configuration
set -euo pipefail
# Reset UFW
sudo ufw --force reset
# Set defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (rate limited)
sudo ufw limit 22/tcp comment 'SSH rate limited'
# Allow web traffic
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'
# Enable logging
sudo ufw logging medium
# Enable IPv6
sudo sed -i 's/IPV6=no/IPV6=yes/' /etc/default/ufw
# Enable UFW
sudo ufw --force enable
# Show status
sudo ufw status verbose
echo "UFW configuration complete"
Ansible Playbook
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 ---
- name: Configure UFW firewall
hosts: webservers
become: yes
tasks:
- name: Install UFW
apt:
name: ufw
state: present
update_cache: yes
- name: Set UFW default policies
ufw:
direction: "{{ item.direction }}"
policy: "{{ item.policy }}"
loop:
- { direction: 'incoming', policy: 'deny' }
- { direction: 'outgoing', policy: 'allow' }
- name: Allow SSH
ufw:
rule: limit
port: '22'
proto: tcp
- name: Allow HTTP/HTTPS
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop:
- '80'
- '443'
- name: Enable UFW
ufw:
state: enabled
Conclusion
Learning to secure Ubuntu server with UFW provides essential network protection through accessible firewall management. UFW balances powerful security with operational simplicity, making it ideal for Ubuntu server administration.
Key takeaways when you secure Ubuntu server with UFW:
- Always configure SSH access before enabling UFW to prevent lockout
- Use default deny incoming policy with explicit allow rules
- Restrict database and sensitive services to specific IP addresses
- Implement rate limiting on SSH to prevent brute-force attacks
- Enable logging for security monitoring and troubleshooting
- Use application profiles for cleaner rule management
- Regular audit rules and remove unnecessary access
- Combine with Fail2Ban for enhanced intrusion prevention
- Document your firewall policy for team knowledge sharing
- Automate UFW configuration for consistency across servers
When you secure Ubuntu server with UFW correctly, you establish foundational network security that protects against the majority of automated attacks and unauthorized access attempts. The straightforward syntax and powerful functionality make UFW the preferred firewall tool for Ubuntu administrators at all skill levels.
Start with basic rules allowing only essential services, then refine your configuration based on actual traffic patterns and security requirements. Regular monitoring of UFW logs reveals attack patterns and helps optimize your firewall rules for maximum protection with minimum operational friction.
- About the Author
- Latest Posts
Mark is a senior content editor at Text-Center.com and has more than 20 years of experience with linux and windows operating systems. He also writes for Biteno.com