Set Up UFW on an Ubuntu VPS Without Locking Yourself Out
Allow SSH first, open only ports 80 and 443, then enable UFW with your session still open. A safe, tested order plus an escape plan if SSH stops working.
The short answer
To set up UFW on an Ubuntu VPS without losing access, allow your real SSH port before you enable the firewall, then allow 80/tcp and 443/tcp and set incoming traffic to deny. Enable with sudo ufw enable, answer the SSH prompt, and test a brand new SSH login while your first session stays open. If you do get locked out, log in through your provider's web console and run sudo ufw disable.
Reading options
On this page
To set up UFW on an Ubuntu VPS safely, allow your SSH port first, then open only the web ports you need, and only then turn the firewall on while your current session stays open. Do it in that order and the firewall starts blocking strangers without blocking you.
Here is the part that catches people: the official ufw manual says that turning the firewall on "may drop existing connections (eg ssh)." If SSH is how you reach the server and you have not allowed it yet, you have just closed the only door you came in through.
By the end of this guide you will have a working firewall that lets in SSH, HTTP and HTTPS, blocks everything else coming in, and comes with a tested way back in if something goes wrong.
What UFW actually is
UFW stands for Uncomplicated Firewall. It is a small command line tool that writes the real firewall rules for you, so you type ufw allow 80/tcp instead of long kernel rule syntax. Ubuntu's security documentation describes it as working "as a frontend for iptables", which is the tool that sets the Linux kernel's network filtering rules.
Think of your server as an office building with thousands of doors, called ports. Each running service, like SSH or your web server, sits behind one of those doors. UFW is the receptionist at the front desk with a short guest list: if you are on the list you get in, and everyone else is turned away.
Two facts are worth knowing before you touch anything. First, Ubuntu's server documentation says plainly that "ufw by default is initially disabled", so a fresh VPS may have the tool but no active firewall. Second, the Ubuntu community wiki says that once enabled, "by default, deny is being applied to incoming". That default is exactly why order matters.
Why this matters: a firewall that denies incoming traffic by default is the safe choice, but it is also the reason you must put SSH on the guest list before you open the door to the receptionist.
Before you start
Go through this list once. It takes five minutes and saves you a support ticket.
- Root or sudo access over SSH to an Ubuntu server (these commands match the Ubuntu 24.04 "noble" ufw manual).
- Your provider's web console (often called VNC, serial console or emergency console in the VPS dashboard). Log in and open it once now, so you know it works before you need it.
- A snapshot or backup of the VPS from your provider's dashboard, if they offer one. This is your undo button for the whole server.
- Your real SSH port. Many servers use 22, but some admins move SSH to another port. You will check this in Step 2.
- A list of services that must stay reachable, for example a website on ports 80 and 443, or a mail server.
- Time: about 15 minutes. Risk: low if you follow the order below, high if you enable first and allow later.
Heads up: if your server runs a hosting control panel such as cPanel or DirectAdmin, check what firewall it already uses before adding UFW. Two firewall tools managing the same rules can fight each other. When in doubt, ask your host or the panel's documentation first. Also check whether your VPS provider has its own network firewall in the dashboard, because traffic blocked there never reaches UFW at all.
Set up UFW step by step
Do these steps in order, in one SSH session, and do not close that session until Step 8 tells you to.
Step 1: Check that UFW is installed and still off
This command prints the ufw version, which proves the tool is installed.
sudo ufw --versionYou should see a line starting with ufw and a version number. If you get command not found, install the package with apt.
sudo apt update && sudo apt install ufwNext, check the current state of the firewall.
sudo ufw status verboseOn a fresh server you will most likely see Status: inactive. If it says Status: active, someone already enabled it. In that case read the rules it lists carefully before you change anything, because some of them may be keeping your session alive.
Step 2: Find the port SSH really listens on
This command asks the SSH server to print its effective configuration and keeps only the port line. The sshd manual describes -T as "Extended test mode", which outputs "the effective configuration to stdout and then exit."
sudo sshd -T | grep -i ^portYou should see something like port 22. If you see a different number, for example port 2222, use that number everywhere this guide says 22.
To double check what is listening on the server right now, list TCP sockets that are listening, with numeric ports and the process name.
sudo ss -tlnpLook for sshd in the last column and note the port next to it. You will also see your web server (for example nginx or apache2) on 80 and 443, plus anything else you may have forgotten about, such as a database.
Quick tip: if you see a database like MySQL listening, you usually do not want to open its port to the whole internet. Leaving it off the guest list is the point of this exercise.
Step 3: Set the default policies
These two commands tell UFW to block all new incoming connections and to allow the server to make outgoing connections (for updates, DNS lookups and so on).
sudo ufw default deny incoming
sudo ufw default allow outgoingThese are the same defaults the community wiki shows in its sample status output, so you are not inventing anything unusual. Since the firewall is still off, nothing changes for your session yet.
Heads up: the ufw manual warns that "existing rules will have to be migrated manually" when you change the default policy. On a fresh setup this does not matter, but on a server with existing rules, list them first so you know what you are changing.
Step 4: Allow SSH before anything else
This is the step that prevents a lock-out. It adds a rule that allows TCP traffic to port 22.
sudo ufw allow 22/tcpIf your SSH port from Step 2 is different, use that number instead. Here is the same rule for a made-up custom port of 2222.
sudo ufw allow 2222/tcp comment 'SSH custom port'The ufw manual confirms that rules can carry a comment, which helps when you read the list six months later and wonder why a port is open.
You may also see guides use sudo ufw allow ssh. Ubuntu's documentation says a service name works when that name is defined in /etc/services. A name cannot know about your custom port, so the number is safer.
Step 5: Allow your web ports
These two commands allow HTTP on port 80 and HTTPS on port 443, which is all a normal website needs.
sudo ufw allow 80/tcp
sudo ufw allow 443/tcpIf you prefer one rule with a label, the manual shows a multi-port form. This version opens 80 and 443 together.
sudo ufw allow proto tcp from any to any port 80,443 comment 'web'Use one style or the other, not both, or you will end up with duplicate rules.
Step 6: Review the rules before you switch them on
While UFW is still inactive, ufw status does not show your rules. This command lists the rules exactly as you typed them, which the manual calls the "added" report.
sudo ufw show addedYou should see your SSH rule and your web rules. Read the SSH line twice and make sure the port matches Step 2.
If you want to see what a rule would do before adding it, the --dry-run flag means "don't modify anything, just show the changes". Ubuntu's server docs give this example.
sudo ufw --dry-run allow httpIt prints low-level firewall rules and changes nothing.
Step 7: Enable the firewall and answer the prompt
This command turns UFW on and makes it start at every boot.
sudo ufw enableBecause you are connected over SSH, the manual says "ufw will prompt when enabling the firewall while running under ssh." It warns that your SSH connection may be disrupted and asks you to confirm. Type y and press Enter.
Heads up: the manual also offers ufw --force enable, which skips that prompt. Do not use it on a remote server. That prompt is your last chance to stop and check that SSH is allowed.
Step 8: Test with a second session before you close the first
Do not close your current terminal. Open a new terminal window on your computer and start a fresh SSH login to the server.
ssh your-user@203.0.113.25Replace the user name and address with your own (and add -p 2222 if you use a custom port). If the new login works, your SSH rule is correct and you can relax. If it hangs or times out, go back to the first session, which is still open, and fix the rule or run sudo ufw disable.
Why this matters: an existing session can survive a rule change that would block a new login. Testing with a brand new session is the only honest test.
Here is a made-up example: Priya moved SSH to port 2200 a year ago and forgot. She runs ufw allow 22/tcp, enables the firewall, and her current session stays up, so she thinks all is fine and logs out. The next morning she cannot connect at all. The second-session test would have caught it in ten seconds.
Optional hardening once the basics work
None of this is required. Add these only after Step 8 passed.
Rate limit SSH logins
A limit rule slows down password guessing. The manual says it "will deny connections if an IP address attempts to initiate 6 or more connections within 30 seconds." This command adds a limited rule for port 22.
sudo ufw limit 22/tcpThen run sudo ufw status numbered. If a plain ALLOW rule for 22 is still listed next to the LIMIT rule, delete the plain one so the limit actually applies (see the next section for deleting by number). For stronger protection against repeated login failures, pair this with a tool like Fail2ban, covered in our guide to protecting SSH with Fail2ban.
Allow SSH only from your own address
If your home or office has a fixed IP address, you can let only that address reach SSH. Ubuntu's server docs show this form; here it uses an example address.
sudo ufw allow proto tcp from 203.0.113.25 to any port 22Test a new session from that address, and only then delete the general SSH rule. Heads up: many home connections change IP address now and then. If yours does, this rule can lock you out on a random Tuesday, so keep the provider console handy or skip this step. Using SSH keys instead of passwords is a gentler win; see setting up SSH key login.
Block one bad address
The manual states that "Rule ordering is important and the first match wins." So to block one address while port 22 is open to everyone else, insert the deny rule at the top of the list.
sudo ufw insert 1 deny from 192.0.2.10Check IPv6 is covered
The manual says IPv6 is enabled by default, and that "Rules that match both IPv4 and IPv6 addresses apply to both IP versions." You can confirm the setting with this command.
grep IPV6 /etc/default/ufwYou should see IPV6=yes. When it is on, ufw status shows extra lines marked (v6) for each rule. That is normal and means your IPv6 address is protected too.
Turn on logging
This command makes UFW log blocked connections, which helps when something mysteriously stops working.
sudo ufw logging onThe manual says logs go to the kernel log facility, and on systems with rsyslog may also go to /var/log/ufw.log. The default level is "low".
How to manage rules later
You will add and remove rules over the life of the server. These are the commands you will actually use.
This command lists every rule with a number in front of it.
sudo ufw status numberedThis command deletes rule number 3 from that list. The manual says "You may also specify the rule by NUM, as seen in the status numbered output."
sudo ufw delete 3Quick tip: numbers shift after every delete. Run sudo ufw status numbered again before each delete, or you may remove the wrong rule, possibly the SSH one.
You can also delete a rule by repeating it with delete in front, which avoids number mistakes.
sudo ufw delete allow 80/tcpIf you install software that ships a UFW profile, sudo ufw app list shows the profile names it knows. Use profiles if you like them, but port numbers are easier to read and check.
How to check it worked
Run these checks right after enabling, and again any time you change rules.
Check 1: Read the status
Run sudo ufw status verbose on the server. You should see Status: active, a line reading Default: deny (incoming), allow (outgoing) as in the community wiki example, and your allow rules for 22, 80 and 443 (plus (v6) copies).
Check 2: Log in again
Open a new SSH session from your computer, as in Step 8. It should log in normally.
Check 3: Load the website
From your computer, request your site's headers. This command fetches headers only and gives up after 10 seconds instead of hanging.
curl -I --connect-timeout 10 https://example.comYou should get an HTTP/ status line back, such as a 200 or a 301 redirect. If you get a timeout instead, port 443 is not reaching the server.
Check 4: Confirm a closed port is closed
If you know a service listens on another port (from Step 2), for example a database on 3306, try reaching it from your computer with this command. A timeout or a refused connection is what you want.
curl -I --connect-timeout 10 http://203.0.113.25:3306Check 5: Survive a reboot
Reboot once during a quiet hour, then log in again and run sudo ufw status. It should still say active, because ufw enable also turns it on at boot.
Troubleshooting
Locked out: SSH just times out
Symptom: ssh hangs, then reports a timeout. Likely cause: SSH was not allowed, or it was allowed on the wrong port. Fix: open your provider's web console, log in as your user, and run sudo ufw disable. The manual says this "unloads firewall and disables firewall on boot", so SSH works again immediately. Add the correct SSH rule, then enable again and repeat the second-session test.
The website stopped loading after enabling
Symptom: the browser spins and then shows a connection timeout. Likely cause: 80 or 443 is missing from the rules, or you only allowed 80 and the site redirects to HTTPS. Fix: run sudo ufw status and add sudo ufw allow 443/tcp (and 80 if missing).
Rules look right but a port is still blocked
Symptom: ufw status shows an allow rule, yet the port does not answer. Likely cause: a firewall in your VPS provider's dashboard blocks the port before traffic reaches the server, or the service itself is not listening. Fix: check the provider's network firewall settings, and run sudo ss -tlnp to confirm the service is listening on that port.
A deny rule does nothing
Symptom: you added ufw deny from an address, but it can still connect. Likely cause: rule order. The first match wins, so an earlier allow rule matched first. Fix: delete your deny rule and add it again with sudo ufw insert 1 deny from 192.0.2.10.
ufw status shows nothing after adding rules
Symptom: you added rules but sudo ufw status only prints Status: inactive. Likely cause: the firewall is not enabled yet, and inactive status does not list rules. Fix: use sudo ufw show added to review them, then enable when ready.
Everything is a mess and you want a clean start
Symptom: too many old or duplicate rules to untangle. Fix: run sudo ufw reset, which the manual says "Disables and resets firewall to installation defaults." It turns the firewall off and asks for confirmation. Then start again from Step 3. Do not add --force here either.
When to ask your host or a developer
Ask for help if your server runs a control panel and you are unsure which firewall it uses, if you run containers or complex networking, or if your provider console does not work. Those setups can have rules outside UFW, and guessing there is how outages happen. If you are setting up a fresh panel server, our DirectAdmin install guide is a good place to plan the firewall from the start.
The one message worth forwarding
If someone else manages the server, send them this:
"Hi, before we enable UFW on the VPS, can you confirm a few things first: which port SSH listens on (sudo sshd -T | grep -i ^port), that we have a working web console login with the provider, and that a snapshot exists. Plan: ufw default deny incoming, ufw default allow outgoing, allow the SSH port, allow 80/tcp and 443/tcp, review with ufw show added, then ufw enable without --force, keeping the current session open and testing a new SSH login before closing it. Rollback is sudo ufw disable from the console."
The whole trick is order: put SSH on the guest list, keep one session open, and test with a second one before you walk away.
Reader questions
Is UFW enabled by default on Ubuntu?
No. Ubuntu's server documentation says ufw is initially disabled, so a fresh server may have the tool installed but no active firewall. Check with sudo ufw status verbose.
Will enabling UFW disconnect my SSH session?
It can. The ufw manual warns that enabling the firewall may drop existing connections such as SSH, which is why you allow your SSH port before running sudo ufw enable.
Should I use ufw --force enable on a remote server?
It is better not to. The --force option skips the confirmation prompt that ufw shows when you enable it over SSH, and that prompt is your last chance to check that SSH is allowed.
How do I get back in if UFW locked me out?
Use your VPS provider's web or emergency console to log in, then run sudo ufw disable. That unloads the firewall and stops it from starting at boot, so you can fix the SSH rule and enable it again.
Does UFW protect IPv6 too?
Yes, IPv6 is enabled by default in ufw, controlled by the IPV6 setting in /etc/default/ufw. Rules that match both address types apply to both, and you will see extra (v6) lines in the status output.
How do I delete a single UFW rule?
Run sudo ufw status numbered to see rule numbers, then sudo ufw delete followed by the number. Numbers change after each delete, so list them again before removing another rule.
What does ufw limit do?
A limit rule denies connections from an IP address that tries to open 6 or more connections within 30 seconds. It is a simple way to slow down repeated SSH login attempts.
Was this guide helpful?
Help us make the next update better.
Sources & further reading
Originally published . About our editorial updates.


