Chapter 1 · Lesson 4 of 19
Server basics

Set up a firewall with ufw

A firewall decides which network connections may reach your server; ufw is Ubuntu's simple front end for it.

By the end you will

Turn on ufw so only SSH, HTTP and HTTPS reach your server, without locking yourself out.

Time
12 min
Level
Beginner
Check
4 questions
You need
  • An Ubuntu server with sudo access
  • An open SSH session to keep during the change

A new server answers on every port that has a program listening. A database you installed for testing, an admin panel or a debug server can end up open to the whole internet without you meaning it. A firewall flips the default: nothing gets in unless you allow it. You then open only the doors you want, usually SSH, HTTP and HTTPS.

How it works#

A firewall is a list of rules the kernel checks for every network packet. Each rule says allow or deny for a certain port, protocol or address. On Linux the rule engine is netfilter, driven through iptables or nftables. Those tools are powerful but terse. ufw (Uncomplicated Firewall) is a small front end that writes the rules for you.

ufw has two defaults for direction: incoming and outgoing. The usual setup is deny incoming and allow outgoing. Your server can still reach out to download updates, but nobody can connect in unless a rule says so. Rules are checked in order, and the first match wins.

Allowing “OpenSSH” uses an application profile, a named bundle of port 22 and TCP. You can also write 22/tcp yourself. Each allow rule is added for IPv4 and IPv6, which is why you see Rules updated (v6).

A worked example: a visitor opens http://203.0.113.10. The request arrives on port 80. ufw checks the rules, finds 80/tcp ALLOW, and lets it through to nginx. A scanner tries port 3306. No rule matches, the default is deny, and the packet is dropped, so the scanner gets no answer. You never had to name 3306, because everything unlisted is blocked.

A host firewall only sees traffic that reaches the machine. A firewall at your provider, if you use one, filters before the traffic arrives. They stack, and either can block you.

Step 1: Allow SSH first#

bash
sudo ufw allow OpenSSH

What you should see: Rules updated and Rules updated (v6). If your SSH runs on another port, allow that port instead, for example sudo ufw allow 2222/tcp.

Step 2: Allow web traffic#

bash
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Port 80 is plain HTTP and port 443 is HTTPS. Keep 80 open even if you serve only HTTPS, because Let’s Encrypt checks and redirects often use it. A reverse proxy usually listens on both.

What you should see: the same Rules updated lines for each command.

Step 3: Turn it on#

bash
sudo ufw enable

Confirm with y. Keep your current session open. Existing SSH connections are normally kept, but a new connection is checked against the rules.

What you should see: Firewall is active and enabled on system startup. The firewall now starts at every boot.

Check it worked#

bash
sudo ufw status verbose

What you should see: Status: active, a default line of deny (incoming), allow (outgoing) and rules allowing 22, 80 and 443. Open a second SSH session to confirm you can still log in. To check from outside, run nc -zv 203.0.113.10 5432 from another machine for a port you did not open. It should time out or be refused.

Edge cases and gotchas#

  • Docker bypasses ufw. A port published with -p 8080:80 is opened through Docker’s own iptables rules, ahead of ufw. ufw deny 8080 will not hide it. Publish to localhost only (see publish container ports safely), for example -p 127.0.0.1:8080:80, or put a reverse proxy in front.
  • IPv6 may have its own gap. ufw handles IPv6 only if IPV6=yes in /etc/default/ufw, which is the default on Ubuntu. If it was turned off, your IPv6 address is unfiltered. Check the file.
  • Changing the SSH port needs a new rule before the change. Allow the new port, test it in a second session, and only then remove the old rule and restart SSH.
  • A provider firewall can block you even when ufw is right. If ports are closed from outside but ufw allows them, check the provider’s firewall settings.
  • Order and numbering matter for deletes. Use sudo ufw status numbered and then sudo ufw delete 3 to remove one rule. Deleting by number twice in a row shifts the numbers, so check again.
  • Rate limiting is available for SSH. sudo ufw limit OpenSSH denies an address that makes many connection attempts in a short time. It helps against bots but can catch you if you open many connections quickly.
  • The firewall is not a fix for weak passwords. An open SSH port with a guessable password is still a risk. Combine ufw with key based login.
  • Allowing a port to one address is possible. sudo ufw allow from 203.0.113.50 to any port 22 proto tcp limits SSH to one address. Do it only if your address never changes, or you can lose access.
  • UDP is separate from TCP. A rule for 53/tcp does not cover 53/udp. Name the protocol you mean.

Troubleshooting#

SymptomLikely causeFix
New SSH login hangs or times out after ufw enableNo allow rule for your SSH portFrom the provider’s console run sudo ufw allow OpenSSH or sudo ufw disable
ufw reports it cannot find a profile named OpenSSHThe OpenSSH profile is not installedUse sudo ufw allow 22/tcp
ufw: command not foundufw is not installedRun sudo apt install ufw
Site works on IPv4 but not on IPv6No v6 rules or IPv6 turned off in ufwCheck IPV6=yes in /etc/default/ufw and run sudo ufw reload
Port is open even though ufw denies itA Docker published portBind to 127.0.0.1 or change the publish
Status: inactive after a rebootufw was never enabledRun sudo ufw enable
Skipping adding existing ruleThe rule is already thereNothing to fix
Logs fill with [UFW BLOCK] linesNormal scan traffic being droppedRead with journalctl -k, or lower logging with sudo ufw logging low

Real-world scenario#

Priya installs a database for a test and forgets about it. Two days later a monitoring email says the server is slow. ss -ltn shows the database listening on 0.0.0.0:5432, open to the world, with a default password.

She enables ufw with SSH, 80 and 443 allowed and everything else denied. From her laptop nc -zv 203.0.113.10 5432 now times out, while the website still loads. She then changes the database password and binds it to localhost.

The firewall bought her time, but she also fixed the cause: a service that did not need to be public.

Quick reference#

TaskCommand
Allow SSHsudo ufw allow OpenSSH
Allow a portsudo ufw allow 443/tcp
Turn onsudo ufw enable
Show rulessudo ufw status numbered
Delete a rulesudo ufw delete 3
Rate limit SSHsudo ufw limit OpenSSH
Turn offsudo ufw disable

Security and safety notes#

  • Allow SSH before you enable the firewall, and keep a session open while you test.
  • Know how to reach the provider’s web console, so you can run sudo ufw disable if you lock yourself out.
  • sudo ufw reset removes every rule. Use it only when you mean to start over.

Next#

Keep an Ubuntu server updated automatically.

Try it: Set up a firewall with ufw

Allow SSH and web traffic, turn the firewall on and check the rules.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1What must you do before sudo ufw enable?
2Does ufw control ports published with docker run -p?
3After enabling, what default for incoming traffic should status verbose show?
4You move SSH to port 2222 but only allowed OpenSSH. What happens when ufw is active?

Frequently asked questions

Can I lock myself out with ufw?

Yes, if you enable it without allowing SSH first. Allow OpenSSH before you run ufw enable, and keep a session open while you test.

Does Docker bypass ufw?

Ports you publish with docker run -p are opened through Docker's own iptables rules, which ufw does not control. Publish only the ports you mean to expose.

Do I still need a firewall if my cloud provider has one?

A provider firewall is a good extra layer in front of the server. A host firewall still protects you if the provider rules are wrong, and it travels with the machine.

Will ufw close ports my running apps use?

Yes. After enabling, any port you did not allow is blocked from outside, including a web app or database you run on the server. Allow what you need before you enable.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios