How to open ports on Ubuntu with UFW: practical firewall guide
Learn how to open, allow, and close ports on Ubuntu using UFW. Configure the firewall step by step with safe rules for HTTP, HTTPS, SSH, and custom ports.
A misconfigured firewall is one of the most common causes of trouble on freshly provisioned Linux servers — either because the application does not respond (port closed) or because the server is overexposed (port open without need). On Ubuntu, UFW (Uncomplicated Firewall) is the default interface and simplifies iptables rule management, keeping the configuration readable and versionable.
This tutorial covers the full flow: enabling UFW without locking yourself out via SSH, opening ports for common services (HTTP, HTTPS, database), creating rules restricted by source IP, verifying status, and removing old rules. The audience is a Linux sysadmin configuring the firewall for the first time on an Ubuntu 22.04 or 24.04 server.
Estimated time: 10-15 minutes to run through every step carefully, including verification. If you only need to open a specific port, jump straight to the “Opening TCP and UDP ports” section.
Prerequisites
You need Ubuntu 22.04 LTS or 24.04 LTS with sudo access, an active and stable SSH session, and knowledge of the SSH port in use (default: 22). UFW comes installed by default — no external package required.
Before you start, confirm which port SSH is running on. If you or your provider changed it to a custom port (e.g., 2222), that information is critical — opening the wrong port means losing access to the server after enabling the firewall.
22/tcp 80/tcp 443/tcp deny incoming, allow outgoing Checking current UFW status
Before adding rules, confirm whether UFW is enabled or disabled. Enabling it with the wrong rules can disconnect you immediately.
Check UFW status:
sudo ufw status verboseIf the output is Status: inactive, the firewall is disabled and no rule is in effect. If it is Status: active, list the existing rules before changing anything.
Identify the SSH port in use by reading the configuration:
sudo grep -i "^Port" /etc/ssh/sshd_configIf the output shows Port 22 (or no line at all), it is on the default. If it shows another number (e.g., Port 2222), take note — you need to allow that port before enabling UFW.
Enabling UFW without first allowing the SSH port drops your current session and prevents reconnection. If this happens and you do not have console access from your provider, recovery requires reinstalling the server.
Allowing SSH before enabling the firewall
This is the most important step. Always allow SSH first, then enable UFW.
Allow the SSH port (use 22 or the custom port identified above):
sudo ufw allow 22/tcpIf SSH runs on a custom port:
sudo ufw allow 2222/tcpThe response Rules updated confirms that the rule was added to the pending configuration. It is not yet active because UFW is still disabled.
Enable UFW:
sudo ufw enableUFW will ask if you want to continue, warning that it may interrupt SSH connections. Confirm with y. If your SSH session does not drop, the previous step worked.
Opening TCP and UDP ports
With the firewall active, open the ports for applications that need to be externally accessible. UFW accepts several syntaxes — choose the clearest one for your case.
Allow HTTP and HTTPS for web services (nginx, Apache, Caddy):
sudo ufw allow 80/tcp
sudo ufw allow 443/tcpAlternative using a predefined profile (more readable in scripts):
sudo ufw allow "Nginx Full"List available profiles with sudo ufw app list.
Allow a UDP port (e.g., internal DNS or game server):
sudo ufw allow 53/udp
sudo ufw allow 27015/udpIf the application uses both TCP and UDP on the same port number (e.g., some game protocols), omit the protocol:
sudo ufw allow 27015Allow a port range (useful for FTP passive or a range of applications):
sudo ufw allow 5000:5100/tcpUse a colon (:) to separate start and end. The range is inclusive on both ends.
Restricting access by source IP
For services that should not be public (database, admin panel, metrics), allow only known IPs.
Allow PostgreSQL only from your application server IP:
sudo ufw allow from 203.0.113.45 to any port 5432 proto tcpReplace 203.0.113.45 with the real IP. To allow an entire network (e.g., a private VPC):
sudo ufw allow from 10.0.0.0/24 to any port 5432 proto tcpApply rate limiting on SSH to mitigate brute-force attempts:
sudo ufw limit 22/tcpThe limit directive blocks connections from the same source that exceed 6 attempts in 30 seconds. It does not replace SSH keys and fail2ban, but adds an extra layer.
Use ufw limit for rate limiting + SSH key authentication (disabling passwords in /etc/ssh/sshd_config) + fail2ban watching /var/log/auth.log. The three together cover 99% of automated attacks without hurting legitimate access.
Verifying active rules
After adding rules, confirm that everything looks as expected.
List all rules with numbering:
sudo ufw status numberedThe output shows each rule with an index ([ 1], [ 2], etc), useful for removing specific rules later. The To column indicates the destination (port on the server), Action is ALLOW/DENY/LIMIT, and From is the allowed source.
Test port connectivity from another machine:
nc -zv YOUR_IP 80If the port is open and the service is responding, the output is Connection succeeded. If the port is open but nothing is listening, it is Connection refused. If the port is closed by the firewall, the command hangs or returns Operation timed out.
Removing old rules
As you reorganize services, rules turn into clutter. Cleaning up keeps the firewall auditable.
Remove a rule by number (use the list from ufw status numbered):
sudo ufw delete 3UFW asks for confirmation showing which rule will be removed. After deletion, the numbers of subsequent rules are reindexed — always run ufw status numbered before each delete in a sequence.
Remove a rule by full specification (an alternative that does not depend on numbering):
sudo ufw delete allow 8080/tcpThis is safer in scripts because it does not depend on rule order.
Troubleshooting
”ufw: command not found”
UFW is not installed (rare on standard Ubuntu, but it happens on minimal images):
sudo apt update
sudo apt install -y ufw
Port allowed but service does not respond
Check whether the service is actually listening on the port:
sudo ss -tulpn | grep :PORT
If nothing appears, the issue is not the firewall — the service is not running or it is bound to 127.0.0.1 (localhost only). For services that should accept external connections, configure them to bind to 0.0.0.0 or to the public IP.
Rules disappear after reboot
UFW persists rules automatically to /etc/ufw/user.rules. If rules vanish after reboot, the service may not be enabled at boot:
sudo systemctl enable ufw
sudo systemctl status ufw
Next steps
With the firewall active and ports configured, consider the following next steps to harden the server:
- Configure fail2ban to monitor brute-force attempts against SSH, HTTP, and other services.
- Switch SSH to key-based authentication and disable password login in
/etc/ssh/sshd_config. - Set UFW logging to medium (
sudo ufw logging medium) and centralize logs via journald or an external system. - Document firewall rules in a versioned runbook — this makes auditing and onboarding other sysadmins easier.
- Study
before.rulesandafter.rulesin/etc/ufw/for advanced scenarios such as NAT, masquerading, and Docker integration.
If you are provisioning this in production and want to focus on the application instead of infrastructure operations, a Hostini VPS ships with Ubuntu LTS and a pre-configured firewall with SSH allowed — you only add the rules for your applications.
Frequently asked questions
What is the difference between 'ufw allow 80' and 'ufw allow 80/tcp'?
Without specifying the protocol, UFW opens both TCP and UDP on the port. Specifying /tcp or /udp restricts the rule to the correct protocol, which is safer and clearer. For web services (HTTP, HTTPS, SSH) always use /tcp; for DNS and games use /udp or both depending on the application.
Do I need to restart UFW after adding a rule?
No. UFW applies rules in real time as soon as you run the allow or deny command. Reload (sudo ufw reload) is only required if you edited configuration files manually in /etc/ufw/ or modified profiles in /etc/ufw/applications.d/.
How do I open a port only for a specific IP?
Use the extended syntax: sudo ufw allow from 203.0.113.45 to any port 5432 proto tcp. This opens port 5432 (PostgreSQL) only for requests coming from IP 203.0.113.45 — useful for databases that should only be accessible from your application server.
Does UFW work with Docker?
Partially. Docker manipulates iptables directly and bypasses UFW rules for ports published with -p. For containers exposed publicly, use the --iptables=false flag on the Docker daemon or configure rules in /etc/ufw/after.rules. In production, consider exposing containers only through a reverse proxy (nginx) with UFW protecting the host.
How do I check which process is using a port before opening it in the firewall?
Use sudo ss -tulpn | grep :PORT to list processes listening on the port. If nothing appears, no service is bound to it — opening it in UFW will not make the port work. You first need to start the service (nginx, mysql, etc) that will respond on that port.
Is it safe to leave port 22 open to any IP?
It works, but it is not ideal. We recommend limiting SSH to known IPs (sudo ufw allow from YOUR_IP to any port 22) or using sudo ufw limit ssh, which blocks excessive connection attempts from the same source. Combine it with SSH keys (disabling password auth) and fail2ban for defense in depth.