How to harden an Ubuntu 24.04 server for production
An ordered checklist for a fresh Ubuntu 24.04 VPS that runs a production app: SSH keys, firewalls Docker can't bypass, fail2ban, updates, Docker, secrets, backups and monitoring. Tested on 24.04.
TL;DR
- In order: update the system, log in with keys as your own user, turn off password and root logins, close every port but SSH, 80 and 443 in a firewall outside the server, and add fail2ban.
- Docker (opens in a new tab) publishes container ports around ufw, so publish only your reverse proxy and bind everything else to
127.0.0.1. - Keep security updates automatic, plan reboots for kernel fixes, rotate Docker's logs and keep secrets in files only root and the app can read.
- Back up off the server, test the restore and monitor from outside: a hardened server you can't restore or don't watch is not production-ready.
On this page
To harden an Ubuntu server for production, you close every way in that your app doesn't need and make the remaining ones hard to abuse. On a fresh Ubuntu 24.04 VPS that runs a web app, do the steps below in order; each links a full guide where it needs more room.
We ran every command on Ubuntu 24.04.5 LTS on 11 November 2026, in containers that run systemd as a server does, with a second container as the outside visitor. We didn't create cloud servers; provider details come from Hetzner (opens in a new tab)'s and DigitalOcean (opens in a new tab)'s documentation.
What it means to harden an Ubuntu server
Server hardening is reducing the attack surface: the services, ports, accounts and settings an attacker could use. The common ways into a small server are not clever: a guessable password login, a database port open to the internet, a dashboard published without a password, unpatched software. This checklist closes those doors first.
It is written for one Ubuntu 24.04 LTS server, rented from a provider such as Hetzner Cloud or DigitalOcean, that runs a web app in Docker Compose behind a reverse proxy. If you haven't deployed the app yet, start with our guide to deploying a web app to a VPS; if an AI builder wrote it, the production checklist for vibe-coded apps covers the code itself.
| Step | What | Full guide |
|---|---|---|
| 0 | Create the server with a key and a provider firewall | This page |
| 1 | Update everything | This page |
| 2 | Your own user, SSH keys, no passwords, no root | Secure SSH on Ubuntu |
| 3 | Firewall: provider's and ufw, and Docker's published ports | Docker ignores your UFW firewall |
| 4 | fail2ban | Secure SSH on Ubuntu |
| 5 | Automatic security updates and reboots | Automatic security updates on Ubuntu |
| 6 | Docker: proxy-only ports, log rotation, the docker group | This page |
| 7 | Secrets and file permissions | This page |
| 8 | Only the services you need | This page |
| 9 | Backups off the server, and a restore test | Backups you can restore |
| 10 | Monitoring from outside | Monitoring a small server |
0. Create the server with a key and a firewall
Set these up when you create the server, before it is on the internet with defaults:
- Choose Ubuntu 24.04 LTS, the version this guide was tested on.
- Add your SSH public key, so your first login uses a key instead of a password. Make one first if you have none:
ssh-keygen -t ed25519. - Attach the provider's firewall with three inbound rules: TCP 22, 80 and 443 (plus UDP 443 if your proxy serves HTTP/3). Hetzner Cloud Firewalls and DigitalOcean Cloud Firewalls are free, and both block inbound traffic that no rule allows. If you always connect from a fixed address, limit TCP 22 to it.
Our guides to deploying a Docker Compose app to Hetzner and deploying to a DigitalOcean Droplet walk through both consoles; our comparison of Hetzner and DigitalOcean helps you choose.
1. Update everything
A new server's image is often weeks old. Update it before anything else, and reboot if the update asks for it:
sudo apt update && sudo apt full-upgrade
ls /var/run/reboot-required && sudo rebootfull-upgrade also installs new dependencies that updated packages need, such as a new kernel package. The file /var/run/reboot-required exists only when an update needs a reboot to take effect.
2. Your own user, SSH keys, no passwords, no root
With password logins off, there is nothing to guess.
Create your own user with
sudo:sudo adduser deployandsudo usermod -aG sudo deploy. Give it a long password:sudoasks for it, and so does the provider's browser console if you ever lock yourself out of SSH.Put your public key in its
~/.ssh/authorized_keys(withssh-copy-id, or by copying root's).Log in as that user in a second terminal and keep the first one open.
Create
/etc/ssh/sshd_config.d/10-hardening.conf:PasswordAuthentication no KbdInteractiveAuthentication no AuthenticationMethods publickey PermitRootLogin no AllowUsers deploy MaxAuthTries 3 LoginGraceTime 30 X11Forwarding noCheck it, read the values in force, and reload (your open session stays connected):
sudo sshd -t sudo sshd -T | grep -E '^(passwordauthentication|permitrootlogin|allowusers) ' sudo systemctl try-reload-or-restart sshOpen a new login as
deployin another terminal. Close the first session only once that works.
Two Ubuntu 24.04 details matter. OpenSSH keeps the first value it reads, and Ubuntu reads the files in sshd_config.d in name order before the main file. Cloud images can carry their own 50-cloud-init.conf with PasswordAuthentication yes; in our test a file named 10-... won over it, one named 60-... didn't. And SSH now starts through a systemd socket, so changing the port takes systemctl daemon-reload and systemctl restart ssh.socket, not just a restart of ssh.
The tests and their output are in our guide to securing an SSH server on Ubuntu.
3. A firewall, and the Docker catch
Allow SSH before you turn ufw on, then deny everything else that comes in. If you moved SSH to another port, allow that port instead of OpenSSH:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verboseOn a server without Docker, that is a working firewall. With Docker, it isn't enough. Docker publishes container ports with its own iptables rules, which redirect traffic to the container before ufw's rules are checked; Docker's documentation calls Docker and ufw "incompatible".
The fixes, all from Docker's documentation and tested in our article on Docker bypassing ufw:
- Publish only the reverse proxy (80 and 443). Everything else either has no
ports:entry and is reached over the Compose network, or is bound to the server only:"127.0.0.1:3000:3000". - Keep the provider's firewall in front from step 0. It is outside the server, so nothing Docker does can open a hole in it.
- Put rules that must live on the server into the
DOCKER-USERchain, loaded at boot before Docker starts.
Then check from another machine, not from the server: nc -zv -w 3 your-server 5432 must not connect.
4. fail2ban
fail2ban reads the login log and blocks an address after repeated failures. With keys only, it is not what keeps attackers out, but it cuts the noise and covers you if password logins are ever turned on by mistake. On Ubuntu 24.04 it watches SSH as soon as it is installed:
sudo apt install fail2ban
sudo fail2ban-client status sshdThe default bans an address for 10 minutes after 5 failures within 10 minutes. A longer bantime in /etc/fail2ban/jail.local, and how to unban yourself, are in the fail2ban section of our SSH guide.
5. Automatic security updates, and a plan for reboots
Ubuntu Server installs security updates by itself once a day, through unattended-upgrades. Confirm it on your server:
apt-config dump APT::Periodic::Unattended-Upgrade # should print "1"
systemctl list-timers 'apt-daily*'
sudo unattended-upgrade --dry-run --debugIt installs security updates only (not Ubuntu's ordinary bug-fix updates), and it never reboots by default. A kernel fix protects you only after a reboot, so either reboot by hand when /var/run/reboot-required appears, or set Unattended-Upgrade::Automatic-Reboot "true" with a quiet Automatic-Reboot-Time in a local file. Docker from Docker's repository and your container images are not covered: update those on your own schedule. Our guide to automatic security updates on Ubuntu has the log files and how to move the update time.
6. Docker: install it carefully, and limit what it exposes
Docker is usually the largest piece of software on the server, and it runs as root. Four settings make it safer:
Install it from Docker's own apt repository, following Docker's instructions for Ubuntu, so you get current releases. Docker 28.0 fixed an old problem where ports published to
127.0.0.1could be reached from other machines on the same network; check yours withdocker version.Publish only the proxy, as in step 3.
sudo docker ps --format 'table {{.Names}}\t{{.Ports}}'shows what is published; only the proxy should show0.0.0.0.Rotate the logs. Docker's default log driver keeps every line forever; Docker's documentation recommends the
localdriver to prevent disk exhaustion. In/etc/docker/daemon.json:{ "log-driver": "local", "log-opts": { "max-size": "10m", "max-file": "3" } }Restart Docker and recreate the containers; existing containers keep their old settings.
Treat the
dockergroup as root. Docker's documentation says the group grants root-level privileges. Add only the user that deploys, and protect that user's key like a root key.
Inside your Compose file, run the app as a non-root user where its image allows it, and give each service only the volumes it needs.
7. Secrets and file permissions
Keep the secrets your app runs with (database passwords, API keys, the backup's password) out of the image and out of git (opens in a new tab), in files only root and the app can read:
sudo chown deploy:deploy /srv/app/.env
sudo chmod 600 /srv/app/.envMake the owner the user that runs docker compose (here deploy, the user your pipeline deploys as): Compose reads .env when it starts the containers, and nobody else needs to. Keep a copy of every secret in a password manager too: a server is something you can lose. If a secret was ever committed to git, rotate it: removing the line doesn't remove it from history. Our guides on scanning a git repository for leaked secrets and environment variables in production cover the app side.
8. Run only what you need
Every listening service is a door. List them:
sudo ss -tulpnOn a hardened Docker host you should see SSH, the proxy (through Docker), and services bound to 127.0.0.1 only. Remove what you don't recognise or don't use (sudo apt remove <package>), and turn off what you can't remove (sudo systemctl disable --now <service>). Admin dashboards (a database UI, Portainer (opens in a new tab), a metrics page) should never be published on the internet: bind them to 127.0.0.1 and reach them through an SSH tunnel or a VPN.
9. Backups off the server, and a restore test
Hardening does nothing for a bad migration, a mistyped command or a lost server. Keep a copy of the data elsewhere:
- dump the database every night with its own tool (
pg_dump -Fcfor PostgreSQL (opens in a new tab)), never by copying its files while it runs; - send the dump, uploaded files and configuration encrypted to a bucket outside the server, for example with restic, keeping several generations;
- add the provider's server backups as a second layer (Hetzner: 20% of the server's price for seven daily copies; DigitalOcean's basic plans: 20% weekly or 30% daily);
- get an alert when a nightly run doesn't happen;
- restore into a throwaway database every month.
CISA's 3-2-1 rule sums it up: three copies, on two kinds of storage, one off-site. The scripts, the timer, the heartbeat and the tested restore drill are in backups for a small production server that you can restore.
10. Monitoring from outside
Hear about problems before your users do:
- an uptime check from outside the server, on your health route, with alerts to your phone;
- disk and memory alerts: a full disk is a common quiet failure, and a short script on a timer catches it;
- logs that rotate (Docker's driver from step 6, and a cap on the system journal).
All of it can be free. The tested script, the log settings and the options for charts are in our guide to monitoring a small server.
Check your work
Once you're done, check what is really in force:
sudo sshd -Tshowspasswordauthentication noandpermitrootlogin no;- from another machine,
ssh -o PubkeyAuthentication=no deploy@your-serverends withPermission denied (publickey); - from another machine, only 22, 80 and 443 answer (
nc -zv -w 3 your-server <port>for the ports you care about); sudo ufw status verboseand the provider's firewall agree;sudo fail2ban-client status sshdshows the jail running;apt-config dump APT::Periodic::Unattended-Upgradeprints"1";sudo docker psshows0.0.0.0only on the proxy;- the last backup restored, and the last test alert arrived.
What this checklist doesn't cover
- CIS benchmarks. The Center for Internet Security publishes detailed hardening benchmarks for Ubuntu, in two levels, that cover far more than this page. Canonical's Ubuntu Security Guide (USG), part of Ubuntu Pro, can audit a server against them and apply them on Ubuntu 24.04. A profile changes many settings at once, so apply it on a test server first and check that your app and Docker still work.
- Compliance frameworks such as SOC 2, ISO 27001, PCI DSS (card data) or HIPAA (US health data). They are about processes, evidence and responsibilities as much as server settings. If your app takes card payments, handles health records or sells to enterprises, find out early which applies.
- Intrusion detection, web application firewalls and DDoS protection. A proxy service in front of the server can add the last two at the network edge; host-based intrusion detection is the next step for servers with valuable data.
- The app itself. The code and its configuration are a separate attack surface: missing authorization checks, an exposed admin route, a public database key with no access rules. The production checklist for vibe-coded apps and our article on the Supabase anon key and Row Level Security cover those.
Doing this with OpsCrew
OpsCrew is an open-source tool that does the same job with AI agents and shows every change before it makes it. On a server it creates at Hetzner Cloud or DigitalOcean, or on a server you already have, it sets up, as its security page lists:
- a
deployuser with key-only SSH, no password logins, and SSH limited to modern algorithms; - a firewall that lets in only SSH and web traffic, fail2ban, and automatic security updates;
- Docker with log limits, with every container port kept on the server except the proxy's 80 and 443;
- HTTPS with TLS 1.2 and 1.3 and security headers, and, behind Cloudflare (opens in a new tab), origin protection so only Cloudflare acting for your zone reaches the server.
On a server you already have, each change is in a host plan you approve first, and SSH and firewall changes undo themselves if they would lock you out. npx opscrew secure then checks the hardening over SSH and the ports that answer from outside, --deep adds Lynis, ssh-audit and testssl.sh, and once your computer is on the app's private network, OpsCrew can close public SSH altogether. For the rest of the checklist it has snapshots with an encrypted copy off the server and a scheduled check that alerts you from outside. OpsCrew is free; you pay the provider for the server, as the pricing page explains.
Key facts
| Fact | Value | Source |
|---|---|---|
| Ubuntu 24.04 SSH start-up | Socket activation (ssh.socket); a systemd generator turns the Port and ListenAddress settings into the socket's settingsSo a port change needs systemctl daemon-reload and systemctl restart ssh.socket, as the comment at the top of Ubuntu's /etc/ssh/sshd_config says. | Ubuntu 24.04 LTS release notes (opens in a new tab)Verified on |
| Automatic security updates on Ubuntu Server | On by default, once a day | Automatic updates, Ubuntu Server documentation (opens in a new tab)Verified on |
| Docker and ufw | Ports published by Docker bypass ufw's rules | Docker documentation, Packet filtering and firewalls (opens in a new tab)Verified on |
| Provider firewalls | Free at Hetzner Cloud and DigitalOcean; inbound traffic no rule allows is blocked | Hetzner Cloud Firewalls overview (opens in a new tab)Verified on |
| Versions in this guide's tests | Ubuntu 24.04.5 LTS, OpenSSH 9.6p1, fail2ban 1.0.2, ufw 0.36.2, unattended-upgrades 2.9.1, Docker Engine 29.9.3, PostgreSQL 18.6, restic 0.16.4Tested on 11 November 2026 in containers running systemd, not on a cloud server. | Ubuntu 24.04 LTS release notes (opens in a new tab)Verified on |
Frequently asked questions
Do I need CIS hardening for my server?
Usually not for a small app, until someone asks for it. CIS benchmarks are long, prescriptive checklists that auditors and enterprise customers recognise. Do the essentials in this checklist first, and adopt a CIS profile when a customer contract, an audit or a regulation calls for it, or when the server holds regulated data.
How long does it take to harden a new VPS?
The essentials in this checklist take an afternoon the first time and much less once you have them as a script or cloud-init file. Backups and monitoring take longest, because they need an outside bucket, an alerting service and a first restore test.
Sources
- OpenSSH server (Ubuntu Server documentation) (opens in a new tab)
- Automatic updates (Ubuntu Server documentation) (opens in a new tab)
- Ubuntu 24.04 LTS release notes (opens in a new tab)
- Ubuntu Security Guide (USG) (opens in a new tab)
- sshd_config(5) (opens in a new tab)
- Packet filtering and firewalls (opens in a new tab)
- Port publishing and mapping (opens in a new tab)
- Configure logging drivers (opens in a new tab)
- Linux post-installation steps for Docker Engine (opens in a new tab)
- Hetzner Cloud Firewalls overview (opens in a new tab)
- DigitalOcean Cloud Firewalls (opens in a new tab)
- Back Up Business Data (opens in a new tab)
Related articles
- Deploying
Cloudflare Tunnel for a self-hosted app: setup, Docker and SSH
What a Cloudflare Tunnel is, quick tunnels and named tunnels, a tested Docker Compose setup with a tunnel token, SSH through Cloudflare Access, and the limits that come with sending every request through Cloudflare.
- AI and DevOps
Do you need a DevOps engineer for a small app?
The DevOps work a small production app needs, what a platform or automation can take over, what still needs a person, what a hire costs per official statistics, and the signs it is time to hire.
- Hosting
Self-hosted Supabase vs Supabase Cloud
What the official self-hosting setup includes, what it leaves to you (backups, upgrades, HTTPS, auth emails, storage, the dashboard), what Supabase Cloud's plans cost, and how to choose between them.