How to Allow Connections from a Specific IP Address in Ubuntu Using UFW

In Ubuntu production server environments, exposing critical administrative services—such as SSH (port 22), MySQL (port 3306), PostgreSQL (port 5432), or web management consoles—to the open internet creates an enormous attack surface. Leaving ports globally accessible invites relentless automated brute-force attacks, port scanners, and credential-stuffing bots.

The standard security hardening practice is restricting administrative ports strictly to trusted static IP addresses, such as your home office IP, a corporate VPN gateway, or a staging proxy. Ubuntu’s Uncomplicated Firewall (UFW) makes binding firewall allow rules to specific IP addresses and subnets remarkably simple.

Step 1: Allow a Single IP Full Access to the Server

If you want a trusted remote workstation or jump box to have uninhibited access to all network ports on your Ubuntu machine:

  1. Open your terminal and connect to your server.
  2. Execute the following UFW command, substituting your actual trusted public IP:
sudo ufw allow from 203.0.113.45

UFW will permit any inbound packet originating from 203.0.113.45 regardless of the destination port.

Step 2: Allow a Specific IP Access to a Specific Port (e.g., SSH)

The principle of least privilege dictates granting access only to the exact port required. To allow your static IP address to connect exclusively to the SSH service:

sudo ufw allow from 203.0.113.45 to any port 22 proto tcp

Similarly, to whitelist a dedicated web application server to communicate with your MySQL database:

sudo ufw allow from 198.51.100.20 to any port 3306 proto tcp

Step 3: Allow an Entire Subnet Range (CIDR Notation)

If your team operates behind an office subnet or a corporate VPN block, you can whitelist the entire address block using standard CIDR notation:

sudo ufw allow from 192.168.1.0/24 to any port 22

This single rule grants access to all 254 IP addresses within the 192.168.1.1 through 192.168.1.254 range while continuing to block the outside world.

Step 4: Verify and Review Numbered UFW Rules

Always inspect your active rule table to confirm proper order and syntax:

sudo ufw status numbered

UFW will print a numbered manifest displaying your source IPs, target ports, and action statuses (ALLOW IN). If you ever need to revoke access for an old IP, delete the rule using its assigned index number (e.g. sudo ufw delete 3).

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.