---
title: "UFW on Ubuntu VPS: firewall rules without losing SSH | StreetHosting"
description: "Set up UFW on an Ubuntu VPS: allow SSH before enable, ufw limit, web and game ports, IPv6, Docker, and the panel console so you never get locked out."
url: "https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps"
type: "page"
language: "en-US"
---

VPS · 10 min · Beginner

Published on May 19, 2026 · Updated on Sep 28, 2026

# UFW firewall on an Ubuntu VPS, from the first enable to Docker

UFW makes the Ubuntu firewall simpler, but one rule in the wrong order locks you out of your VPS. Learn how to enable it without losing SSH, open only what you need, deal with Docker, and get back in through the console if something goes wrong.

By [Equipe StreetHosting](https://streethosting.com.br/en/autores#equipe-streethosting) · StreetHosting infrastructure and support team

[Security and hardening](https://streethosting.com.br/en/guides/topics/security) [Linux administration](https://streethosting.com.br/en/guides/topics/linux) [Containers and Docker](https://streethosting.com.br/en/guides/topics/docker)

Summarize with:

[](https://chat.openai.com/?q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "ChatGPT") [](https://claude.ai/new?q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Claude") [](https://www.google.com/search?udm=50&aep=11&q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Google AI Mode") [](https://x.com/i/grok?text=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Grok") [](https://www.perplexity.ai/search/new?q=Summarize%20the%20key%20points%20of%20this%20StreetHosting%20guide%3A%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps.%20Highlight%20the%20step-by-step%20instructions%2C%20the%20prerequisites%20and%20the%20most%20common%20mistakes. "Perplexity")

Share:

[](https://x.com/intent/tweet?text=UFW%20on%20Ubuntu%20VPS%3A%20firewall%20rules%20without%20losing%20SSH&url=https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps "Share on X") [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps "Share on Facebook") [](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps "Share on LinkedIn") [](https://wa.me/?text=UFW%20on%20Ubuntu%20VPS%3A%20firewall%20rules%20without%20losing%20SSH%20https%3A%2F%2Fstreethosting.com.br%2Fen%2Fguides%2Fvps%2Fufw-firewall-ubuntu-vps "Share on WhatsApp")

For agents: Copy as Markdown [.md](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps.md)

[Previous How to secure SSH on a Linux VPS: keys, passwords, fail2ban](https://streethosting.com.br/en/guides/vps/secure-ssh-linux-vps) [Next How to set up swap on Ubuntu on a VPS](https://streethosting.com.br/en/guides/vps/set-up-swap-ubuntu-vps)

In this guide 8 sections

* [The default deny mindset](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#mentalidade-default-deny)
* [A safe sequence before the first enable](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#fluxo-seguro-primeiro-enable)
* [Rate limiting and restricting the source](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#limit-e-origem)
* [Common rules: websites, games and databases](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#regras-comuns-http-game-db)
* [Reviewing, deleting and logging rules](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#gerenciar-regras)
* [UFW with Docker and other pitfalls](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#ufw-com-docker-e-pitfalls)
* [If you lock yourself out: the panel console](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#console-vnc)
* [Firewall, Anti-DDoS and where to run it](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#onde-rodar)

Quick answer

On an Ubuntu VPS, set UFW to **deny incoming**, allow **SSH on its real port** before enabling, check with `sudo ufw show added` and only then run `sudo ufw enable`. Swap the SSH allow for limit, open only the ports with an active service, publish containers on 127.0.0.1, and keep a local password so you can use the panel console if something goes wrong.

## The default deny mindset[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#mentalidade-default-deny)

UFW is a simplified front end for the Linux kernel firewall. It ships with Ubuntu Server, but turned off. The policy you want is default deny: every incoming connection is refused, and every open port is an exception with a reason behind it. That prevents the accidental exposure of internal services such as a database, a control panel or a test endpoint that stayed up after a deploy.

The classic case is opening 5432 to test PostgreSQL from home and forgetting to close it. Within a few hours the database shows up in automated scans and starts receiving login attempts. With default deny and a periodic review of the rules, that kind of leak drops considerably.

Two ideas guide the rest of this guide. First: UFW evaluates rules in order and the first match wins, so a deny for one IP has to come before the general allow for that port. Second: the firewall is only one layer of remote access. It works best alongside [secure SSH on a Linux VPS](https://streethosting.com.br/en/guides/vps/secure-ssh-linux-vps), with key-based login and remote password login disabled.

## A safe sequence before the first enable[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#fluxo-seguro-primeiro-enable)

The sequence below sets the policies, allows SSH, shows the rules that are about to take effect, and only enables the firewall at the end:

`sudo ufw status verbose sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow OpenSSH sudo ufw show added sudo ufw enable sudo ufw status numbered`

1. The OpenSSH profile opens port 22/tcp. If your SSH uses another port, allow that one instead, for example `sudo ufw allow 2222/tcp`. Check the real port with `sudo ss -tlnp | grep ssh`.
2. show added lists the pending rules without activating anything. If SSH is not in that list, stop.
3. enable warns that it may drop SSH connections and asks for confirmation. Answer y. In scripts, use `sudo ufw --force enable`.
4. Without closing the current session, open a second terminal and log in fresh. Only after you get in through it should you consider the firewall ready.

For a safety net, schedule the firewall to turn itself off before you enable it: `sudo systemd-run --on-active=5min /usr/sbin/ufw disable`. If you lose access, UFW shuts down on its own in five minutes. If everything went well, cancel it with `sudo systemctl stop` followed by the timer name the command printed.

To change the SSH port, the order is: allow the new port in UFW, change the SSH configuration, test the new port from another session, and only then delete the old rule. On Ubuntu 24.04, SSH is socket-activated, so the new port only takes effect after `sudo systemctl daemon-reload` and `sudo systemctl restart ssh.socket`.

## Rate limiting and restricting the source[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#limit-e-origem)

With the firewall up, the next step is to make the SSH rule smarter. limit replaces allow and temporarily denies any IP that opens 6 or more connections in 30 seconds:

`sudo ufw limit OpenSSH sudo ufw status numbered`

It cuts off bots that reconnect in a loop, but it has limits. It counts connections, not wrong passwords, so a bot that tries several passwords over the same connection gets through. And tools that open many connections in a row, such as deploy scripts, rsync in a loop or remote editor extensions, can get blocked by mistake. To block by login attempt, use [Fail2Ban on your VPS](https://streethosting.com.br/en/guides/vps/fail2ban-ssh-vps-setup).

The strongest protection is not accepting connections from anyone but you. If you have a static IP, or a VPN, restrict the source:

`# only one IP can reach SSH sudo ufw allow from 203.0.113.10 to any port 22 proto tcp comment 'office SSH' # SSH only from inside the WireGuard VPN sudo ufw allow in on wg0 to any port 22 proto tcp comment 'SSH via VPN' # after testing, remove the open rule sudo ufw delete limit OpenSSH`

Many residential connections in Brazil have a dynamic IP or sit behind CGNAT, and the address changes without notice. In that case, a VPN is more reliable than an IP list. The setup is in the [WireGuard VPN on a VPS](https://streethosting.com.br/en/guides/vps/wireguard-vpn-vps) guide, and the complete access strategy is in [protecting SSH against brute force](https://streethosting.com.br/en/guides/infrastructure/protect-ssh-from-brute-force).

## Common rules: websites, games and databases[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#regras-comuns-http-game-db)

Open only the ports that have an active service behind them, in the narrowest form possible. When no protocol is given, UFW opens TCP and UDP at the same time, which is useful for games that use both.

| Service                | UFW rule                                               | Notes                                                                          |
| ---------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------ |
| SSH                    | sudo ufw limit OpenSSH                                 | Or the custom port with /tcp; ideally with a restricted source                 |
| HTTP and HTTPS website | sudo ufw allow 'Nginx Full'                            | Equivalent to 80/tcp and 443/tcp; port 80 is used for Let's Encrypt validation |
| Minecraft Java         | sudo ufw allow 25565/tcp                               | If you enable query, also allow 25565/udp                                      |
| Minecraft Bedrock      | sudo ufw allow 19132/udp                               | Bedrock uses UDP only; 19133/udp for IPv6                                      |
| FiveM                  | sudo ufw allow 30120                                   | Without a protocol it opens TCP and UDP, which FiveM uses                      |
| CS2                    | sudo ufw allow 27015                                   | UDP for the game and TCP for RCON                                              |
| PostgreSQL or MySQL    | sudo ufw allow from APP\_IP to any port 5432 proto tcp | Never open to any source                                                       |

The command `sudo ufw app list` shows the ready-made profiles that packages install, such as OpenSSH and the Nginx profiles. For websites, the norm is to keep only 80 and 443 public and have the application listen on localhost behind the reverse proxy. Databases, Redis and internal panels also stay on localhost; if another machine needs access, allow only its IP.

## Reviewing, deleting and logging rules[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#gerenciar-regras)

Rules pile up over time. The everyday commands:

`# list with numbers sudo ufw status numbered # delete by number (the numbering shifts afterwards, list again) sudo ufw delete 4 # delete by the rule itself sudo ufw delete allow 8080/tcp # block an IP ahead of the allow rules sudo ufw insert 1 deny from 198.51.100.23 comment 'scanner' # log blocked packets to /var/log/ufw.log sudo ufw logging low`

* **Comments:** every rule accepts `comment 'reason'` at the end. Six months from now, you will want to know why 8443 is open.
* **IPv6:** in `/etc/default/ufw`, the IPV6 option defaults to yes, and every per-port rule gets a copy marked v6. If your domain has an AAAA record, make sure the IPv6 rules follow the same policy; otherwise a service blocked over IPv4 may still be reachable over IPv6.
* **Logs:** at the low level, blocked packets show up tagged UFW BLOCK, with source IP and port. Levels above medium generate too much volume for continuous use.
* **Starting over:** `sudo ufw reset` turns the firewall off and deletes every rule, keeping a backup copy. Before the next enable, allow SSH again.

## UFW with Docker and other pitfalls[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#ufw-com-docker-e-pitfalls)

This is the pitfall that exposes the most databases on a VPS. When you publish a port with `-p 5432:5432`, Docker creates its own rules that redirect traffic straight to the container. That traffic goes through the forward chain, not the input chain where the UFW rules live. The result: `ufw status` does not show the port, and it is open to the internet.

The ways out, from the simplest to the most involved:

* **Publish on localhost only:** in compose, use `"127.0.0.1:5432:5432"` under ports. The container is reachable from the VPS itself and from the reverse proxy, but not from outside.
* **Change the Docker default:** with `{ "ip": "127.0.0.1" }` in `/etc/docker/daemon.json` and a Docker restart, every port published without an explicit IP listens locally only.
* **Filter in the user chain:** for containers that need to be public with a restricted source, create rules in the `DOCKER-USER` chain, which Docker reserves for that. The `ufw-docker` project automates that integration.

Installing Docker itself is covered in the [install Docker on Ubuntu](https://streethosting.com.br/en/guides/vps/install-docker-ubuntu-vps) guide. Two other common mix-ups: a port allowed in UFW where nothing answers is usually a service listening only on 127.0.0.1, not a firewall problem; and Fail2Ban bans on Ubuntu 24.04 live in their own nftables table, so they do not show up in ufw status.

* Save the output of sudo ufw status numbered before big changes
* Check sudo ss -tlnp and the container ports after every deploy
* Test from another machine whether the database port answers
* Write down the removal date for every temporary exception
* Review the numbered rules once a month

## If you lock yourself out: the panel console[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#console-vnc)

Even when you are careful, it happens: a rule in the wrong order, a mistyped port, a forgotten reset. The way out is the VPS console, on the service page in the client area. It works through the hypervisor, like a monitor and a keyboard plugged into the machine, and does not go through the network or the firewall.

The detail that catches a lot of people: there is no SSH key in the console. You log in with a username and local password. If you only ever log in with a key and never set a password, set one now, before you need it:

`sudo passwd your-user`

This does not reopen password login over SSH if that is disabled; the password is only for the console and for sudo. Inside the console, the fix is usually one line: `sudo ufw allow OpenSSH`, or `sudo ufw disable` to catch your breath and redo the rules calmly. If your password has symbols and the login fails, suspect the console keyboard layout, which may differ from yours.

## Firewall, Anti-DDoS and where to run it[](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#onde-rodar)

UFW decides what gets into the VPS, but it only acts after the packet has arrived. A volumetric attack saturates the link before any rule is evaluated, and that can only be solved on the provider's network. On the other side, an open port 443 lets through everything that comes over HTTP, and attacks on the application call for another layer. The differences are in [network firewall vs application firewall](https://streethosting.com.br/en/guides/infrastructure/network-firewall-vs-application-firewall).

The [StreetHosting VPS plans](https://streethosting.com.br/en/vps) are KVM with root access, so UFW, nftables and Docker work without any virtualization restriction. They sit in São Paulo, with Anti-DDoS included on the network and a console in the control panel for when the firewall locks the door. To learn and host a small website, the Xeon VPS with 2 vCPU and 2 GB costs R$ 23.00 per month, and the entry-level Ryzen 9 9950X costs R$ 40.00. With Docker, a database and a reverse proxy on the same machine, the Ryzen with 2 vCPU and 4 GB DDR5, at R$ 66.00, gives you more headroom.

In this guide

* [The default deny mindset](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#mentalidade-default-deny)
* [A safe sequence before the first enable](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#fluxo-seguro-primeiro-enable)
* [Rate limiting and restricting the source](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#limit-e-origem)
* [Common rules: websites, games and databases](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#regras-comuns-http-game-db)
* [Reviewing, deleting and logging rules](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#gerenciar-regras)
* [UFW with Docker and other pitfalls](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#ufw-com-docker-e-pitfalls)
* [If you lock yourself out: the panel console](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#console-vnc)
* [Firewall, Anti-DDoS and where to run it](https://streethosting.com.br/en/guides/vps/ufw-firewall-ubuntu-vps#onde-rodar)

## Frequently asked questions

I enabled UFW without allowing SSH. How do I get access back?

Open the VPS console from the service page in the client area, log in with your username and local password, and run sudo ufw allow OpenSSH, or the port you use. The console works through the hypervisor and does not go through the firewall. Without a local password set, the console will not help, so create one before touching any rules.

Why doesn't UFW block my Docker container's port?

Because Docker forwards traffic for published ports through a firewall path that UFW's input rules never evaluate. Publish the port on 127.0.0.1 only and put a reverse proxy in front, or create rules in the chain Docker reserves for the user.

What is the difference between ufw allow and ufw limit?

allow accepts every connection on the port. limit accepts too, but denies an IP that opens 6 or more connections in 30 seconds. It is good for SSH, because it cuts off bots that reconnect in a loop, but it is not suited to website or game ports, where many connections in a row are normal.

Do I need to block outgoing traffic too?

On most VPS, no. The default allow outgoing keeps updates, DNS and API calls working. Restricting outbound traffic makes sense in very sensitive environments, but it requires allowing every needed destination and breaks things easily if done without an inventory.

Does UFW protect the VPS against DDoS?

Not against volumetric attacks. UFW drops packets once they have already reached the VPS, and a large attack saturates the link before that. That layer is handled on the provider's network, by the Anti-DDoS. UFW handles ports and sources, and limit only helps against too many connections on a single port.

Next step

See VPS plans

Root VPS in Brazil with NVMe and Anti-DDoS.

[See VPS plans](https://streethosting.com.br/en/vps)

[See Ryzen VPS Ryzen 9 9950X VPS in São Paulo with root access, NVMe and gamer Anti-DDoS.](https://streethosting.com.br/en/vps/ryzen) [See Xeon VPS Xeon VPS for steady workloads, automation and long-running projects.](https://streethosting.com.br/en/vps/xeon)

## Related guides

[VPS Intermediate How to secure SSH on a Linux VPS: keys, passwords, fail2ban SSH is usually the first target on any VPS with a public IP. This guide walks through a practical routine that cuts the risk without complicating your day: an ED25519 key, password-free login, admin access through sudo, blocking of automated attempts and a periodic review of authorized keys. 4 min Read guide](https://streethosting.com.br/en/guides/vps/secure-ssh-linux-vps) [VPS Intermediate How to set up Fail2Ban on a VPS: SSH, Nginx and repeat offenders Fail2Ban reads your logs, spots the IPs that fail too often and bans them in the firewall. Learn how to set it up on Ubuntu 24.04, where the package defaults change how jails behave, and how to manage bans day to day. 8 min Read guide](https://streethosting.com.br/en/guides/vps/fail2ban-ssh-vps-setup) [Infrastructure Intermediate Protect SSH from brute force: a layered strategy Minutes after an IP goes live, bots start trying root and leaked passwords on SSH. This guide builds the defense in layers, from sshd\_config to a VPN, without locking your team out of the server. 8 min Read guide](https://streethosting.com.br/en/guides/infrastructure/protect-ssh-from-brute-force)

[← Back to the Guide Center](https://streethosting.com.br/en/guides)
