The objective is to enable UFW firewall, deny all incoming ports however only allow SSH port 22 on Ubuntu 18.04 Bionic Beaver Linux

Operating System and Software Versions

  • Operating System: - Ubuntu 18.04 Bionic Beaver


Privileged access to your Ubuntu 18.04 Bionic Beaver will be required.


  • # - requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
  • $ - requires given linux commands to be executed as a regular non-privileged user

Other Versions of this Tutorial

Ubuntu 20.04 (Focal Fossa)


Check a current firewall status

Check your firewall status. By default the UFW firewall will be disabled:
$ sudo ufw status
Status: inactive

Block all incoming traffic

First, we can block all incoming traffic using the following linux command:
$ sudo ufw default deny incoming
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

Allow SSH incoming traffic

Depending on our needs we can enable SSH incoming traffic from all sources:
$ sudo ufw allow OpenSSH
Another option is to allow only a specific source IP address to connect to our port 22. For example let's allow only IP address:
$ sudo ufw allow from to any port 22 proto tcp
Alternatively, we can allow entire subnet. For example
$ sudo ufw allow from to any port 22 proto tcp

Subscribe to our NEWSLETTER and receive latest Linux news, jobs, career advice and tutorials.

Enable Firewall

Please note, UFW will not disconnect your current SSH connection of the session used to enable your UFW firewall. All other SSH connections, may be disconnected:
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

Check status

$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp (OpenSSH)           ALLOW IN    Anywhere                  
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)
FIND LATEST LINUX JOBS on LinuxCareers.com
Submit your RESUME, create a JOB ALERT.
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
Get extra help by visiting our LINUX FORUM or simply use comments below.