Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Install and Configure the UFW Firewall on Ubuntu

Set default rules, allow SSH, web traffic and other services, turn UFW on and manage the rules.

Firewall2 min read

What UFW does

UFW (Uncomplicated Firewall) is the easy front end for the Linux firewall. You allow or block traffic by port, service or address with short commands. It is installed on Ubuntu but turned off by default.

Install UFW

sudo apt update
sudo apt install ufw

Set the default policy

Block all incoming connections and allow all outgoing ones:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow the basic services

Warning: Allow SSH before you enable the firewall on a remote server. If not, you will lock yourself out.
  • SSH for remote management:
sudo ufw allow ssh

If SSH uses another port, for example 2222: sudo ufw allow 2222/tcp.

  • HTTP for normal websites:
sudo ufw allow 80/tcp comment 'Allow HTTP'
  • HTTPS for secure websites:
sudo ufw allow 443/tcp comment 'Allow HTTPS'

(With Apache or Nginx you can also use the application profiles: sudo ufw allow 'Nginx Full' or sudo ufw allow 'Apache Full'.)

More rules

Allow a port range:

sudo ufw allow 40000:40100/tcp

Allow one IP address to a port:

sudo ufw allow from 203.0.113.10 to any port 3306

Block a port or an address:

sudo ufw deny 25/tcp
sudo ufw deny from 198.51.100.7

Limit SSH to slow down brute force attempts:

sudo ufw limit ssh

Turn the firewall on

sudo ufw enable

Answer y to the question.

Check the status

sudo ufw status
sudo ufw status verbose
sudo ufw status numbered

Delete a rule

By number:

sudo ufw status numbered
sudo ufw delete 3

By rule:

sudo ufw delete allow 80/tcp

Logging

sudo ufw logging on

Logs are written to /var/log/ufw.log.

Reset or turn off

Turn off the firewall:

sudo ufw disable

Remove all rules and start again:

sudo ufw reset

Notes

  • UFW works on IPv4 and IPv6 if IPV6=yes is set in /etc/default/ufw.
  • Docker can bypass UFW rules for published ports. Bind container ports to 127.0.0.1 or use the DOCKER-USER chain.
  • Rules are kept after a reboot.

Quick recap

  • Default deny incoming, allow SSH, 80 and 443, then sudo ufw enable.