How to Set Up a Firewall on Ubuntu VPS with UFW

UltaHost banner for "How to Set Up UFW Firewall on Ubuntu VPS" showing managed Ubuntu VPS features including NVMe SSD storage, integrated caching, and 99.99% uptime
Shares

Firewalls are necessary if your Ubuntu VPS has direct online access. You want to keep your VPS secure from unauthorized access. Without a properly configured UFW firewall VPS, any service on your VPS accessible on the Internet is subject to being probed or attacked unless you take effort to limit access.

VPS owners can use firewall rules to diminish attacks. This action allows them to control which services can be accessed publicly. If you do not have any firewall rules set on your VPS, you may inadvertently expose unnecessary ports and applications that can then be attacked by automated attack scripts every day.

This guide explains how to configure UFW on an Ubuntu VPS. It covers inbound rules, SSH access, optional rate limiting, logging and verification. Commands assume a sudo-capable account. Keep an existing SSH session and a working recovery console available while changing access rules.

Key Takeaways

  • Exposing unnecessary services in a public VPS without a firewall means that more vulnerabilities are available.
  • It is more convenient when it comes to managing iptables rules using clear syntax and commands.
  • Failure to allow access will mean that you lock yourself out of the server right after the installation.
  • Access only the necessary services such as SSH, HTTP, HTTPS to improve security.
  • Ufw limit will assist in mitigating brute-force attacks on SSH services.
  • Audit and delete unused rules as often as possible.

What Is UFW?

UFW (Uncomplicated Firewall) is a simple tool that can help manage a Linux firewall. It works with iptables/netfilter to allow you to use simple commands to configure the firewall instead of complicated rules written in the form of text files.

On an Ubuntu VPS, UFW is used to do the following:

  • Block or allow ports to/from the network
  • Restrict the exposure of your service to others on the internet
  • Manage incoming traffic coming in from the internet
  • Prevent unauthorized attempts to gain access
  • Make VPS Security easier to manage

For the Ubuntu VPS Administrator, UFW provides a good balance between ease of use and the ability to control servers.

Why Use a Firewall With a VPS?

A VPS will have a public IP address and is subject to constant scanning by people and bots looking for exposed services, guessable passwords/credentials, and exploitable applications. Without firewall rules, there may be unnecessary services that can be reached over the internet.

Risks commonly associated with lack of firewall rules include:

  • SSH Brute Force Attacks
  • Database Ports Open to the Internet
  • Exposed Applications that are Running on Public IP Addresses
  • Unauthorized Remote Access Attempts
  • Increased Attack Surface

Keep the current SSH session open, allow the actual SSH port and test a second login before closing your recovery route.

Ubuntu firewall documentationEditorial guidance

Installation and Verification of UFW

UFW may already be installed, but it is not necessarily enabled. Check its current state:

sudo ufw status

In case it is not installed:

sudo apt update
sudo apt install ufw

Then check firewall status again:

sudo ufw status verbose

Critical Pre-activation Action for UFW

Before enabling UFW, keep your current SSH session open and confirm that the provider recovery console works. Record the existing rules with sudo ufw show added. Confirm the actual SSH listener and any provider-level firewall rules before making changes.

Enabling UFW without allowing SSH access may result in you being locked out from accessing your VPS right away.

Inspect the listening sockets and effective OpenSSH configuration. Configuration snippets and socket activation can affect the actual port; do not rely only on a grep of the main configuration file:

sudo ss -ltnp
sudo sshd -T | grep '^port '
systemctl status ssh.socket --no-pager

If SSH really uses port 22, allow the OpenSSH profile after checking sudo ufw app info OpenSSH. For a custom port, allow that exact TCP port instead; a default profile does not automatically follow SSH configuration changes.

sudo ufw allow OpenSSH

Or alternatively, explicitly allow port 22 access:

sudo ufw allow 22/tcp

Review the configured rules before activation. Unlike ufw status, which reports the active firewall state, this also helps inspect rules while UFW is inactive:

sudo ufw show added

Only enable UFW after the correct SSH allow rule is in place. After enabling, test a second SSH connection and each required service from another machine. Keep the original session open until those checks succeed.

Basic UFW Commands You Should Know About

Activate UFW

sudo ufw enable

Deactivate UFW

sudo ufw disable

Check Firewall Status

sudo ufw status

Detailed status

sudo ufw status verbose

Reload Rules

sudo ufw reload

Reset All Rules

sudo ufw reset

Proceed with caution with UFW reset commands on production VPS systems, since all firewall rules will be deleted.

Enabling VPS Common Ports

There are some basic services that most VPS configurations will need.

Enable SSH

sudo ufw allow 22/tcp

Enable HTTP

sudo ufw allow 80/tcp

Enable HTTPS

sudo ufw allow 443/tcp

Enable a Different SSH Port

# Example only: use your actual SSH port
sudo ufw allow 2222/tcp

Enable Port Ranges

sudo ufw allow 6000:6005/tcp

These are examples, not a list to apply in full. A server without a website does not need public HTTP/HTTPS; a server using a custom SSH port does not need port 22 opened as well.

In case of Linux servers configured to carry out custom tasks, employing a correctly set Linux VPS allows administrators to have complete control over the firewall policies and exposed services.

Blocking Specific Services or Ports

You can block services or ports via the use of deny rules.

Blocking a Particular Port

sudo ufw deny 25/tcp

Blocking Telnet Service

sudo ufw deny telnet

Blocking All Incoming Connections

This is the suggested policy:

sudo ufw default deny incoming
sudo ufw default allow outgoing

This policy will block any unsolicited incoming connections while permitting all outgoing traffic.

Blocking Excessive SSH Connections

One of the services which is often attacked is SSH.

The UFW utility has support for rate limiting.

Enable SSH rate limiting with this command:

sudo ufw limit OpenSSH

Or:

sudo ufw limit 22/tcp

Rate limiting can reduce repeated connection attempts from one source; it does not replace SSH keys, updates or other authentication controls. An existing broad SSH allow rule can take precedence. Review numbered rules and replace that rule carefully rather than assuming a later limit rule overrides it.

Outbound Traffic Control (Egress Filtering): Firewall configuration is often about management of incoming connections. Control implementation for outbound traffic may increase the overall level of security of a VPS too.

What if an application becomes infected by malicious software? the fact that there are no outbound filters may cause it to:

  • Establish a connection to servers.
  • Download further malware components. 
  • Extract important data.
  • Join botnets.

You can use UFW to configure egress filtering. VPS allows all forms of outbound traffic in most cases. Such restrictions may prove useful for more security-oriented VPS configurations.

Optional egress filtering is an advanced change, not part of the basic deny-incoming/allow-outgoing setup. Allow every required dependency, including DNS and time synchronisation, before blocking outbound traffic. The examples below are incomplete for many applications:

sudo ufw allow out 53
sudo ufw allow out 80/tcp
sudo ufw allow out 443/tcp
sudo ufw allow out 123/udp
# Add the rest of your application dependencies before this step:
sudo ufw default deny outgoing

Note that outbound restrictions should be applied with care. Because tight controls may prevent software updates and normal program operation.

Allowing Application Ports

Open a port only if a service must be reached through the VPS network. Database services should normally remain on loopback or a private network. If remote database access is necessary, restrict it to a trusted source address and configure the database authentication and listener separately.

Here are some examples:

MySQL database

sudo ufw allow from YOUR_IP to any port 3306 proto tcp

The MySQL example above deliberately limits the source instead of exposing the database to the whole Internet. Replace YOUR_IP with the trusted client address. Apply the same restriction to PostgreSQL:

Equivalent restricted rule with an explicit comment:

sudo ufw allow from YOUR_IP to any port 3306 proto tcp comment 'Trusted database client'

PostgreSQL database

sudo ufw allow from YOUR_IP to any port 5432 proto tcp

Node.js application

sudo ufw allow 3000/tcp

Example game server

sudo ufw allow 25565/tcp

Always allow only those ports that are being used.

Viewing and Deleting Rules

Since firewall rules keep changing, regular audits need to be performed.

Numbered Firewall Rules Listing

sudo ufw status numbered

Results:

[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 80/tcp ALLOW IN Anywhere

Deletion of the rule based on the number:

sudo ufw delete 2

Delete specified rule:

sudo ufw delete allow 3000/tcp

Regular auditing helps eliminate unnecessary risks.

Logging and Monitoring Firewall Actions

There is an option in UFW to monitor firewall actions through logging.

Enabling logging

sudo ufw logging on

Log level set to Medium

sudo ufw logging medium

The location of the log file is:

/var/log/ufw.log

Live monitoring logs can be done using:

sudo tail -f /var/log/ufw.log

Considerations about Logging: Firewall logs can become very useful in the matter of troubleshooting and detecting malicious behavior. Essential to understand the effect of logging on the system.

The more you turn up the level of logging, the more logs will be created, especially on VPS servers that face the internet where constant scanning is conducted.

Some of the potential concerns are as follows:

  • Consumption of more disk space
  • More logs that need to be managed regularly
  • More I/O operations on highly-targeted servers
  • Increased difficulty in analyzing logs

Make sure that you rotate the logs properly so that they do not grow uncontrollably. For instance:

/var/log/ufw.log

Docker and provider firewalls: Docker-published container ports can bypass the UFW filtering path. Review Docker firewall integration, bind private services to loopback and test exposure externally. Keep provider firewall rules aligned with the host policy.

Common UFW Errors to Take Care of

Enabling UFW without the correct SSH rule: this can block new logins. Keep the original session and recovery console available, and verify the real listening port first.

  • Allowing Too Many Ports: Ports that aren’t needed by the programs running shouldn’t be exposed.
  • IPv6 Firewall Error: When using IPv6 on the server, configure UFW accordingly.

Review file:

sudo nano /etc/default/ufw

Verify setting:

IPV6=yes

Check both address families when the VPS has IPv6. Enabling IPV6=yes alone does not prove that the resulting rules or upstream provider firewall allow only the intended services. Verify the active IPv4 and IPv6 rules after reloading.

Allowing Your Database Server to Be Internet-Accessible: Database servers running services like MySQL or PostgreSQL need to have public access only if really required.

Disregarding Firewall Maintenance: Unused rules accumulate over time and increase complexity and risk.

UFW Command Cheat Sheet That Can Help You Out

ActionCommand
Enable firewallsudo ufw enable
Disable firewallsudo ufw disable
Show statussudo ufw status
Show numbered rulessudo ufw status numbered
Allow SSHsudo ufw allow OpenSSH
Allow HTTPsudo ufw allow 80/tcp
Allow HTTPSsudo ufw allow 443/tcp
Block a portsudo ufw deny 25/tcp
Limit SSH attemptssudo ufw limit OpenSSH
Delete a rulesudo ufw delete RULE
Reload firewallsudo ufw reload
Reset firewallsudo ufw reset
Enable loggingsudo ufw logging on

Why Firewall Rules are Key to VPS Security?

Proper firewall configuration is an important starting point for hardening any VPS instance.

While strong passwords and software updates might make up for some security weaknesses, unnecessary public access will not go unnoticed. Proper firewall rules can help:

  • Minimize attack surfaces
  • Prevent unauthorized access
  • Minimize service exposures
  • Restrict brute force attacks
  • Increase overall infrastructure security stance

Internet-facing servers should consider proper firewall management an important aspect of baseline security management.

Why UltaHost is Right for Ubuntu VPS Security

Ubuntu VPS instances offer total control over the server environment, including firewall policy enforcement and service restrictions.

UltaHost offers Linux-based VPS hosting environments that include:

  • Root level access
  • Firewall management capabilities
  • Administration of Linux-based services
  • Application-based access restrictions
  • Hardening procedures

This allows VPS users maximum flexibility when using UFW for securing Ubuntu VPS.

Conclusion

A UFW firewall helps reduce the network attack surface of an Ubuntu VPS. Allow the actual SSH port before activation, expose only the required services and verify new connections afterward. Keep rules under review alongside authentication, software updates and backups.

FAQs

Which ports must I allow in a VPS firewall?
How can I see the firewall rules in UFW?
Does UFW help prevent SSH brute-force attacks?
Can UFW help secure my Ubuntu VPS?

Ask UltaAI

Your domain and hosting advisor.


Usama Sajid

A word wizard passionate about making technology simple. The list of topics which I have covered includes VPS hosting, cloud computing, cyber security, server management, and website performance. Follow me for simplified tech jargon.

Related Posts