Qvantor logo QvantorInfrastructure, explained plainly
Guides

UFW Firewall Setup for a New Ubuntu Server in Ten Minutes

A fresh Ubuntu server on a cheap VPS starts receiving login attempts and port scans within minutes of booting, and by default nothing stops those packets from reaching whatever happens to be listening.

Terminal window on a laptop showing firewall rules beside a small server rack with blinking lights

A fresh Ubuntu server on a cheap VPS starts receiving login attempts and port scans within minutes of booting, and by default nothing stops those packets from reaching whatever happens to be listening. A proper UFW firewall setup closes every port you did not choose to open, and on a new machine it takes about ten minutes if you do the steps in the right order.

UFW stands for Uncomplicated Firewall. It is a front end for the kernel's netfilter rules, and it ships with Ubuntu, so there is nothing to install on most images. The catch is that the order of commands matters. Enable it before you allow SSH and you lock yourself out of a machine you can only reach over SSH. This guide walks through the safe sequence, the rules most small servers need, and the one trap that catches almost everyone who runs Docker.

Before you start your UFW firewall setup

Check three things first. It takes a minute and saves an awkward support ticket.

  • Know your SSH port. Run sudo ss -tlnp and look for sshd. Most servers use 22, but some providers or past admins move it to something like 2222.
  • Find your provider's console. Almost every VPS panel has a browser console that works even when the network is firewalled. Open it once now so you know where it is.
  • List what is listening. The same ss -tlnp output shows every service bound to a port. Anything you do not recognise is worth investigating before you decide whether to allow it.

If you have not already switched to key based logins, do that first. A firewall limits who can knock on the door, but key only SSH decides who can open it. It also helps to have unattended upgrades for automatic security patches running, so the services you do expose stay current.

The safe order of commands

Run these as a user with sudo rights. Read each one before pressing enter.

  1. Check the current state. sudo ufw status verbose. On a new image you should see "Status: inactive".
  2. Set the defaults. sudo ufw default deny incoming and then sudo ufw default allow outgoing. Incoming traffic is blocked unless a rule allows it, and the server can still reach package mirrors, DNS and your backup target.
  3. Allow SSH before anything else. sudo ufw limit 22/tcp. Swap 22 for your real port. The limit keyword allows the connection but blocks an address that opens six or more connections within 30 seconds, which slows down password guessing scripts.
  4. Allow your web ports if you serve sites. sudo ufw allow 80/tcp and sudo ufw allow 443/tcp. Port 80 is still needed for most certificate renewals even if every visitor ends up on HTTPS.
  5. Enable it. sudo ufw enable. It warns that the command may disrupt existing SSH connections. Because you allowed SSH in step 3, it will not.
  6. Test from a second terminal. Keep your current session open and start a new SSH login. If the new one connects, you are safe to close the old one.

That is the whole core setup. Running sudo ufw status numbered now shows each rule with a number, twice: once for IPv4 and once for IPv6. UFW handles both as long as IPV6=yes is set in /etc/default/ufw, which is the default on current Ubuntu releases.

Rules most small servers need

Beyond SSH and web traffic, the right rules depend on what the box does. Here are the common cases and the commands that match them.

ServiceRuleNotes
WireGuard VPNallow 51820/udpUDP, not TCP. Easy to get wrong.
Mail server (SMTP)allow 25/tcpAlso 587 for submission and 993 for IMAPS
Admin panel on one IPallow from 203.0.113.10 to any port 8080Replace with your own static address
Databaseno ruleBind it to localhost and keep it closed
Monitoring agentallow from 10.0.0.0/24 to any port 9100Private network range only

Restricting a rule to a single source address is the most underused feature in UFW. If your admin dashboard only needs to be reached from your office line or from inside a WireGuard VPN for remote access, there is no reason for the rest of the internet to see it at all.

To remove a rule, run sudo ufw status numbered, note the number, and run sudo ufw delete 4. Delete one at a time and check the list again, because the numbers shift after every deletion.

The Docker trap that bypasses UFW

This is where the usual advice falls short. Plenty of tutorials say UFW plus a default deny policy means your server is locked down. If you run Docker, that is not true.

When you publish a container port with -p 8080:80 or a ports entry in a compose file, Docker writes its own iptables rules in the nat table and the DOCKER chain. Those rules are evaluated before UFW's rules ever see the packet. The result: ufw status shows port 8080 as closed, and the whole internet can reach it anyway. People find this out when a test database with no password shows up in a breach report.

There are two practical fixes for a small server:

  • Bind published ports to localhost. Write 127.0.0.1:8080:80 instead of 8080:80. The container is then reachable only from the host, and a reverse proxy on 443 forwards traffic to it. This is the simplest fix and the one we use on every box.
  • Filter in the DOCKER-USER chain. Docker leaves this chain alone, so rules added there do apply. It works, but it means maintaining raw iptables rules alongside UFW, which defeats the point of a simple tool.

If you followed our guide to Docker Compose for local development, the same compose files can go to a server unchanged. Just audit every ports line before they do.

Logging and checking that it works

Turn on logging at a modest level with sudo ufw logging low. Blocked packets then appear in /var/log/ufw.log with the source address, destination port and protocol. On a public server expect hundreds of entries a day, mostly scans of ports 23, 3389 and 5900 from automated tools. That is normal background noise and a sign the firewall is doing its job.

To confirm from the outside, run a scan from a different machine: nmap -Pn your.server.ip. You should see only the ports you allowed. If anything else shows as open, check whether Docker published it. Repeat the scan after every new service you deploy, because that is when mistakes creep in.

A firewall pairs well with a tool that reacts to behaviour. UFW blocks ports, while Fail2ban reads logs and bans addresses that keep failing logins. Running both costs almost nothing in memory on a 1 GB VPS.

Frequently asked questions

Does UFW start automatically after a reboot?

Yes. Once you run sudo ufw enable, the service is set to load at boot and your rules are restored from /etc/ufw. You can confirm after a restart with sudo ufw status, which should say active.

What happens if I lock myself out with UFW?

Use your provider's browser console, which connects through the hypervisor rather than the network. Log in there and run sudo ufw allow 22/tcp or sudo ufw disable, then fix the rules properly. This is why it is worth finding that console before you start.

Is UFW enough to secure a server on its own?

No. It reduces what is exposed, but anything you deliberately open, such as a web app on 443, still needs to be patched and configured safely. Combine it with key only SSH, automatic security updates and regular backups for a sensible baseline.

IV
Ilkka Varis

Ilkka has run mail servers for small companies since the days of hand edited DNS zones.

More posts by Ilkka

More in Guides

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto