How to Setup and Configure Firewall with UFW on Ubuntu 18.04. This demo is tested on Google Cloud and it will also work on any Ubuntu and Debian servers.
UFW or Uncomplicated Firewall, is a front-end to iptables which provides an easy-to-use interface and a great way to secure your server.
UFW is installed by default in Ubuntu, for some reason if it is not installed you can install by typing the following command.
sudo apt install ufw
You can check the status (active or inactive) of UFW using this command.
sudo ufw status
Right now you will see it in inactive state.
Setup Firewall Rules
Now you can add the rules and then enable it. If you enable the Firewall now, you will get blocked from your terminal because you haven’t allowed connections on port 22 which is SSH.
Go ahead and add the rule to allow connections for SSH.
sudo ufw allow ssh
This command is basically a shorthand for this command.
sudo ufw allow 22/tcp
If you are using SSH on custom port you can enable the port with this.
sudo ufw allow 2222/tcp
Allow UFW for Port Ranges
You can also specify port ranges with UFW. To allow ports 3000 through 6000, use the command.
sudo ufw allow 3000:6000/tcp
For UDP you can use this.
sudo ufw allow 3000:6000/udp
Allow IP Addresses
You can also specify IP address to allow connections. For example, if you want to allow connections form a specific IP address you can use this sample below
sudo ufw allow from 38.58.345.143
On the other hand you can also deny connections from ports or IP address or ranges.
sudo ufw deny 8080/tcp
Delete Firewall Rules
A simple and effective way to delete a rule is using the rule number. Take note of the rule number you need to delete using this command.
sudo ufw status numbered
Now you will get the number of your rule and then you can delete it.
sudo ufw delete [number]
Once you have added all rules you need you can enable firewall. Make sure you have allowed connections for SSH.
sudo ufw enable
If you want to disable UFW firewall you can use this command.
sudo ufw disable
To reset firewall to it’s default settings, you can do this with this command.
sudo ufw reset