Logo

Home Server 101 - Part 1: Locking Down Bare Metal

Author

Cole

Date Published

Preface, this is the start of a series, leave a comment if you have suggestions for future posts. I built my setup by accident over a decade or so. I learn by doing, so when I first setup my server, I did it so I would have a development playground that I had complete control over. That's meant building and rebuilding this server from scratch many times physically and in terms of the software stack. A pleasure, a pain, a challenge, it's what you make of it. I did most of it by picking a project, and standing it up fully virtualized. Easily repeatable. I did it mostly by stumbling through manuals and experiments. This post is me sharing what I've learned like it's a class. The title is mostly a joke, but the 101 aspect of it will be respected. So if some sections feel over explainy, that's why. That being said, some things won't be explained

  • Installing OSs
  • Basic Linux concepts/commands, this guide assumes a basic understanding of UNIX terminal usage (it's a Headless server)
  • Dual-booting this stack with Windows or other OSs, I would not recommend this
  • Running this stack on WiFi
  • Comparable OSs to Ubuntu, Ubuntu is just a preference and the free Pro license is a quick way to a baseline level of OS security
  • Your public IP and home network topology, too much variability and loaded concepts
  • Your router, it's login, and whether or not it supports port forwarding, do your research
  • DNS, loaded concept, just need a basic understanding
  • Subnets, loaded concept, just need a basic understanding

Now, in terms of hardware, a home server doesn't mean a brand-new piece of hardware, it could be a retired workstation, a mini PC, an old gaming tower, anything that can boot Ubuntu really. Regardless, whatever it is, it just needs power and an internet connection, this is your Bare Metal Server (a.k.a. Host). If you follow this guide, by the end of it you'll either have a locked-down server, or the idea of one at least, that is on the public internet behind a reverse proxy, serving a Jellyfin library and a blog on your own domain. With enough monitoring that you can see what it is doing. The same principles that apply to doing this for Jellyfin/Blog will be applicable to any service you want to try and stand up in the future on the same stack.

A few guiding lights for my home server efforts are least privilege, scalability, and repeatability. Repeatability means, learn the concepts and keep detailed notes, the next progression after that is scripting repeatable tasks. In terms of notes, I personally write ADRs and Incident Response docs when decisions and incidents happen, and I keep a running list of ideas. Scalability in the sense that containers with their infrastructure defined as code can be deployed virtually and scaled horizontally. That means instead of increasing the number of CPU cores or RAM a server has to support demand, you can create more containers, replicating them and routing traffic to the one with the least demand. Least privilege means assume nothing is allowed, close every port first, then open the specific ones you need. That starts with locking down the bare metal.

The Overall Order:#

  1. Install Ubuntu, attach a free Ubuntu Pro subscription, and let it harden itself
  2. Lock the host down with the firewall, denying everything inbound except SSH from your own network
  3. Forward two ports at the router and pair each with a matching firewall rule
  4. Point DNS at your public IP in Cloudflare and keep it current automatically
  5. Run the container stack so that only the reverse proxy is reachable from outside, with everything else on a private Docker network
  6. Add monitoring (Portainer, Dozzle, Netdata) and automation (Watchtower, cloudflare-ddns)

This is the setup my own server actually runs, trimmed down. A few placeholders run through the examples, consistently, so once you know your own values you can swap them in wherever they show up: my server's address, 192.168.0.161 (yours will differ, you'll find it in section 1), my LAN range, 192.168.0.0/24 (use whatever your router hands out), my domain, colekujawa.com, and you, standing in for whatever username you create on the server. Wherever this guide prints one of those, replace it with your own and it's correct everywhere it appears. Another pattern I'd suggest matching as-is rather than swapping: the SSH port. I personally recommend something like port 1021, and the reverse proxy at 172.16.0.253 on the container network (that address is almost certainly free on your side too). One companion post goes deeper than the baseline needs: kernel hardening.

What you need first#

You can skip the domain name if you just want local access, but that will disable functionality for many services if they can never reach your server from the web. DNS and domain management are a small cost/effort if you let Cloudflare do the heavy lifting, and follow the Dynamic DNS section in this guide.

  • A domain name. Any registrar will work, runs about $5-12 a year. You point it at your house or wherever your server is situated in section 4.
  • A second computer on the same network, running Windows, macOS, or Linux. You do the OS install at the server's console (monitor and keyboard, or the board's IPMI), then connect from this machine and run everything else from your desk, as if the server were headless.

Get your PC ready#

If you plan on always signing into your server using a keyboard, mouse, and monitor hooked up to it, you can skip to the Install Docker section. If you want remote access, there's two things you'll need on a second computer, before you touch the server.

VS Code. Install it from code.visualstudio.com, then add the Remote - SSH extension. That is the whole client, they've got a handy guide for setting it up.

An SSH key, this stays on your PC forever, only the public half ever goes near the server. Open a terminal, PowerShell on Windows or Terminal on macOS and Linux, and run:

1ssh-keygen -t ed25519 -C "you@your-pc"

When it asks for a passphrase, set one. It's the only thing standing between “someone gets this file” and “someone has your server.” It'll ask for it more than you'd like at first, Move to your desk covers how to make that a one-time thing per login instead.

Private Ranges#

This has to be covered to explain ranges used later. Three IP ranges are private. The Internet Engineering Task Force directed the Internet Assigned Numbers Authority to reserve these ranges (those are very real organizations lol). They never appear on the public internet, and every home network reuses them:

  • 10.0.0.0/8
  • 172.16.0.0/12
  • 192.168.0.0/16

Your home network likely hands out something like 192.168.x.x addresses. Docker builds its own networks and pulls them from the 172.16 block by default. This post deliberately puts the container network on 172.16.0.0/24: it is obviously not the LAN, so every firewall rule can tell "a device in my house" (192.168.x.x) apart from "traffic between containers" (172.16.x.x). When 172.16.0.253 shows up later, that is the reverse proxy holding a fixed address on the container network.

1. Ubuntu and the free Pro subscription#

I use Ubuntu Server LTS, it's a preference, I won't be covering all the different OSs that this guide would also likely work just fine on, but the pro subscription and what the Ubuntu Security Guide system does for hardening to CIS benchmark compliant levels is not easily done. This guide assumes you have secured to a similar level, you are going to be exposing services on a device on your home network, to the world, I strongly advise you do this on Ubuntu with always free for personal use Pro subscription. Download the current LTS ISO, write it to a USB stick, install it. A few things matter during the installer:

  • Create your user account and remember that it is the first account on the machine, so it gets UID 1000. Containers will run as that same UID later so their files land in your home directory owned by you, with no sudo needed to manage them. Avoid using sudo with Docker as much as possible, it wrecks permissions.
  • SSH should be an option, and you should set it up. Tick "Install OpenSSH server" and leave "Allow password authentication over SSH" on. You'll copy your key across in "Move to your desk" and turn password auth off later in the guide.
  • Skip the extras, what ends up bundled in LTS ISOs is usually out of date, and not hard to get outside of the initial setup. You don't need the featured server snaps or the installer's version of Docker.
  • Keep the disk layout simple. I would advise starting with an SSD for the OS/docker stack, and adding media drives later. In terms of file organization, you'll always start in ~ (home). So that's where I put my projects dir, where everything I work on is housed.

A note on the text menus. Several steps in this section drop into a full-screen blue or pink menu with no mouse: the installer itself, needrestart right after the big apt upgrade below, and dpkg-reconfigure in the Ubuntu Pro step. You may need to use tab and arrow keys to move, Space to toggle, Enter to confirm. When needrestart asks which services to restart, take the default and hit OK. Often times you do not need to do a full restart, simply restarting effected services is enough and Ubuntu does a good job or recommending which ones to restart, and you can select more if needed from there, but default is good enough most of the time.

Note the server's address#

On first boot the server (most likely) picks up an address from your router by DHCP. Find it on the login screen, or run:

1ip -4 addr

You'll get a few blocks. Ignore lo, that's loopback (127.0.0.1), every machine has it. The one you want is your wired network card. Its name reflects where it sits on the board, so on modern Ubuntu it is rarely eth0, it will be something like enp2s0, eno1, ens18. Under it, the line you want reads inet <address>/<prefix> ... scope global:

12: enp2s0: <BROADCAST,MULTICAST,UP,LOWER_UP> ...
2 inet 192.168.0.161/24 brd 192.168.0.255 scope global dynamic enp2s0

192.168.0.161 is the address, use it everywhere this guide writes 192.168.0.161. The /24 on the end is your subnet size, and you'll want that number for the firewall rules in section 2.

If more than one line looks plausible, this settles it. It prints the exact interface and address the box uses to reach the internet:

1ip route get 1.1.1.1
2# 1.1.1.1 via 192.168.0.1 dev enp2s0 src 192.168.0.161

dev is your interface, src is your address.

In your router, set the server to have a static IP/reservation for that address. This is essential to routing all of the traffic to the reverse proxy which will be running on the server. From their the reverse proxy handles the heavy lifting.

Move to your desk#

That should be it for working directly at the server, if you had it plugged into a monitor you can disconnect it now. It's time to test remote connection. Open a terminal on your PC (I recommend via VS Code), macOS/Linux Terminal, Windows PowerShell, or VS Code's own integrated terminal (Terminal menu → New Terminal), which just runs one of those same shells inside the editor; the dropdown next to its + tells you which. If you're on Windows without a strong preference, Git Bash (bundled with Git, which you'll likely want anyway) matches every bash command in this guide exactly, and is what the first command below assumes.

SSH in using the username and credential you created on the server, at the server's IP:

1ssh you@192.168.0.161

The first time, you'll get a prompt asking whether to trust the server's key fingerprint, type yes. Then it asks for your password. On Unix systems, passwords type with no feedback at all, typically no indication that you're inputting anything at all, until you hit enter or it times out. Trust. Type your password, hit enter. If you get it wrong, try again, more carefully.

Copy your key up so the password isn't needed again. This works from macOS, Linux, Git Bash, or WSL, it appends your public key to the server's trusted list:

1cat ~/.ssh/id_ed25519.pub | ssh you@192.168.0.161 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

(macOS and most Linux desktops also ship a shortcut for this exact thing, ssh-copy-id you@192.168.0.161, same result, less typing, use it if you have it.)

In native PowerShell (no Git Bash/WSL), same idea, different syntax:

1Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub | ssh you@192.168.0.161 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

Log out, back in, and confirm it does not ask for a password:

1ssh you@192.168.0.161

Now hand it to VS Code. Add an entry to your SSH config, indentation is important and not a suggestion, ~/.ssh/config (C:\Users\<you>\.ssh\config on Windows, create it if it's missing, no file extension):

1Host homeserver
2 HostName 192.168.0.161
3 User you
4 Port 22
5 IdentityFile ~/.ssh/id_ed25519

Port 22 for now, I recommend you change it to 1021 after section 2. Now, in VS Code: open the Command Palette, then Remote-SSH: Connect to Host, pick homeserver. A new window opens attached to the server, with a green SSH: homeserver badge in the bottom-left. Open its integrated terminal; the rest of this guide runs there.

One thing worth flagging here: you set a passphrase on your key back in “Get your PC ready,” so you'll keep getting asked for it. That's a different prompt from the server's account password you just eliminated, it's local, unlocking your own private key file, not talking to the server at all. VS Code treats every folder you open in its Explorer as its own connection, and fully closing VS Code drops the connection entirely, so both of those re-trigger it.

I usually keep my VS Code opened to the ~ directory. Don't worry about opening any directories now though, and don't harden anything yet. SSH is still on port 22 and the firewall is off, which is fine for a few minutes on a box only your own network can reach.

Then update and reboot the host (VS Code should reconnect on its own):

1sudo apt update && sudo apt full-upgrade -y
2sudo reboot

Install Docker#

Docker is the virtualization environment we'll be using, It's logo represents the Docker whale as a container ship, full of containers, get it? It is an industry standard with rigorous protocols/definitions for hosting images (the base of a container is an image) that make them universally available, easy to use, upgrade, and manage. I personally love docker images for their extensibility, you can modify running containers pretty easy. Install Docker Engine from the official guide, using the apt repository method (not the docker.io Ubuntu package, which lags a long way behind):

docs.docker.com/engine/install/ubuntu

That install includes the Compose v2 plugin. Compose is going to come up again and again, it's a companion to Docker, it allows you to define containers as code, I'll provide examples later. Massively extensible, and allows reproducing the same environment every single time. The docker-compose.yaml file will become THE definition of all the services running on your server. So check that both the Docker version landed and Compose as well, then add yourself to the docker group:

1docker --version
2docker compose version # "docker compose", with a space, is the v2 plugin
3sudo usermod -aG docker $USER

If docker compose version errors, the plugin didn't come along; add it:

1sudo apt install docker-compose-plugin

Log out and back in for the group to take effect. docker group membership is root-equivalent for container operations, so treat SSH access to this account as full control of the host.

Run ip -4 addr again now and you'll see a new docker0 entry on a 172.x address (and once the stack in section 5 is running, a br-… bridge and a row of veth… pairs too). Those are Docker's virtual networks. Your LAN address is still the 192.168.x.x one on the physical card.

Ubuntu Pro#

Now that we're on the host and ready to start building our stack, we need to secure our host first. Canonical gives Ubuntu Pro away for personal use on up to five machines, with no trial period and no card. We're going to do that now. What it turns on:

  • ESM (Expanded Security Maintenance) extends security patches for the main and universe repositories from five years to ten. Most of what you install on a server comes from universe.
  • Livepatch applies critical kernel fixes without a reboot.
  • USG (Ubuntu Security Guide), which audits the machine against the CIS benchmark and applies most of it for you. Covered just below.

Get a token from ubuntu.com/pro/dashboard, then attach it and enable the services:

1sudo pro attach <your-token>
2sudo pro enable esm-infra esm-apps livepatch usg
3sudo pro status

ua-timer now runs daily and applies ESM security updates and Livepatch fixes on its own. Add the standard unattended-upgrades pipeline on top for everything else:

1sudo apt install unattended-upgrades -y
2sudo dpkg-reconfigure --priority=low unattended-upgrades

dpkg-reconfigure opens a full-screen dialog: answer Yes to "Automatically download and install stable updates?".

Let USG harden the box for you#

We're going to run USG. It audits the machine against the CIS benchmark, one line per rule, pass or fail, with the fix for each, and it can apply almost all of them itself:

1sudo usg audit cis_level1_server

That writes a scored report you can open in a browser. You could work through it by hand. Or you point USG at a profile and let it do the work.

There are two CIS levels, each with a server and a workstation variant:

  • Level 1 (cis_level1_server) is the "will not lock you out or break normal use" tier: password and lockout policy, auditd, filesystem mount options, turning off protocols and services you are not running.
  • Level 2 adds defense-in-depth that gets in your way on a machine you actually log into: aggressive audit rules that fill the disk, short session timeouts, blacklisted kernel modules. Right for a bastion host, tiresome for a home server.

I run Level 1 Server. Applying it as-is fights the setup in exactly one place: CIS wants a host firewall configured, and its checks for that expect nftables or iptables-persistent, not UFW. So generate a tailoring file, an XML overlay that switches specific rules off, and disable the firewall rules, since UFW plus the DOCKER-USER chain from section 2 already do that job:

1sudo usg generate-tailoring cis_level1_server tailor.xml

Open tailor.xml. Each rule is a line like <xccdf:select idref="xccdf_org.ssgproject...rule_..." selected="true"/>. Find the ones for the host firewall, search the file (or the audit HTML) for firewall. In the current Level 1 Server profile they are rules 3.2 and 3.3, but the numbers shift between benchmark versions, so match on the description, not the number. Set selected="false" on those, add a comment saying why, save.

1sudo usg fix --tailoring-file tailor.xml
2sudo reboot
3sudo usg audit --tailoring-file tailor.xml

The post-reboot audit should come back mostly green. Mostly, not all, and it can drift over time, this audit is easy to re-run in the future when you may have stronger opinions about how you want things configured. What is left is a short list you are accepting on purpose: the firewall rules you tailored out, plus anything that would break a service you actually run. Going through that list is in the kernel hardening post, along with the sysctl and SSH-crypto tightening USG does not cover.

2. Lock the host down#

Order matters here. Every step either proves a new way in works or closes an old one, and never the second before the first. Keep the SSH session you have open, and test each change from a second one before you rely on it. As long as your host isn't in a remote data center, any lockout scenario is as simple as going back to the server and plugging in peripherals.

Harden sshd#

Put these in a drop-in file, /etc/ssh/sshd_config.d/10-homelab.conf. A drop-in wins over the main config and over anything USG's fix changed, so this is the one place your SSH settings live:

1Port 1021
2PermitRootLogin no
3PasswordAuthentication no
4KbdInteractiveAuthentication no
5MaxAuthTries 4
6AllowUsers you@192.168.0.*

AllowUsers takes user@host glob patterns, not CIDR, so 192.168.0.* is how you write "from my LAN". Once your PC's address is stable (give it a DHCP reservation too), you can tighten 192.168.0.* down to that one address. In the future you may want to extend it to allow tailscale or another VPN service in, but for now, your local network should be sufficient.

sudo systemctl restart ssh. Your VS Code connection stays up (an open SSH session survives the restart), so leave it alone. Open a separate terminal on your PC (a local PowerShell or Terminal, not the VS Code one, which is on the server) and connect on the new port:

1ssh -p 1021 you@192.168.0.161

Only once that lands do you carry on. Change Port to 1021 in the homeserver entry in your ~/.ssh/config, the one VS Code uses, so its next reconnect lands on the new port.

Port 1021 is just an unused high port; almost any is free, and moving off 22 drops nearly all of the drive-by scanner traffic (noise reduction, not real security). PasswordAuthentication no is safe now because you have logged in with your key several times already. Cipher, key-exchange, and MAC tightening is in the kernel hardening post.

Turn on the firewall#

Ubuntu ships with UFW, a front-end over iptables. Deny everything inbound and everything forwarded, allow outbound, then allow SSH back in from your own network only (192.168.0.0/16 covers the usual 192.168.x.x home range, use yours):

1sudo ufw default deny incoming
2sudo ufw default allow outgoing
3sudo ufw default deny routed
4sudo ufw allow from 192.168.0.0/16 to any port 1021 proto tcp
5sudo ufw enable
6sudo ufw status verbose

ufw enable warns it may disrupt SSH; say yes, your current session survives (only new connections use the new rules). sshd is already on 1021 and you have just proven you can reach it there, so it cannot lock you out. From outside your house SSH is now not reachable at all. For a shell while you are away from home, use Tailscale (a full post later in the series), never a forwarded port.

deny routed matters once Docker is running, which is next.

This baseline assumes IPv4 only. Locking IPv6 down is in the kernel hardening post.

The Docker and UFW problem#

Docker writes its own iptables rules into a chain that sits ahead of UFW's in the FORWARD path, so a container with a published port, ports: - 8096:8096, is reachable from anywhere that can route to your host, and ufw status will still say "active" while that port is open. deny routed alone does not stop it, because Docker's rules run first.

The fix is a DOCKER-USER chain that sends Docker's forwarded traffic back through UFW. Add this block to the end of /etc/ufw/after.rules, before you start any containers:

1# BEGIN UFW AND DOCKER
2*filter
3:ufw-user-forward - [0:0]
4:DOCKER-USER - [0:0]
5
6# let the LAN and container-to-container traffic through untouched
7-A DOCKER-USER -j RETURN -s 192.168.0.0/16
8-A DOCKER-USER -j RETURN -s 172.16.0.0/12
9
10# send everything else through UFW's forward rules
11-A DOCKER-USER -j ufw-user-forward
12
13# drop unsolicited inbound from outside the LAN into the container networks
14-A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16
15-A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12
16-A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 192.168.0.0/16
17-A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 172.16.0.0/12
18
19-A DOCKER-USER -j RETURN
20COMMIT
21# END UFW AND DOCKER

This block is from chaifeng/ufw-docker, the project that worked this fix out. You can paste it by hand as above (replacing your local IP range, the 172.16 range can be left exactly as is) or install their ufw-docker script and run ufw-docker install to have it written for you.

sudo ufw reload to apply it. Now the rule is: any device on your LAN can reach any published container port, and nothing from the internet can, unless you add an explicit rule for it. A container with a published port and no matching rule is LAN-only, which covers Portainer, Dozzle, Netdata, and the NPM admin page.

Add the LAN trust rules and reload so container-to-container and LAN access keep working:

1sudo ufw allow from 192.168.0.0/16
2sudo ufw allow from 172.16.0.0/12
3sudo ufw reload

3. Forward two ports at the router#

Two gates have to line up for anything to be reachable from the internet: the router has to forward the port, and the host firewall has to route-allow it to the container. Miss either one and the service stays private.

The router already has the server on a fixed address from section 1. The only change now is to forward TCP 80 and TCP 443 to that address. That is HTTP and HTTPS respectively. Nothing else.

On the host, allow those two ports in and route them to the reverse proxy's container IP (the compose file below pins it to 172.16.0.253):

1sudo ufw allow in to any port 80 proto tcp
2sudo ufw allow in to any port 443 proto tcp
3sudo ufw route allow proto tcp to 172.16.0.253 port 80
4sudo ufw route allow proto tcp to 172.16.0.253 port 443

Those route allow lines are the second gate. Most containers on my server have a published port but no route rule, so they are reachable from the LAN and nowhere else.

The public footprint of the server is now two ports, both landing on the reverse proxy. Since the proxy isn't running, it's hitting an empty address and likely getting a 500 error. We'll stand the service up later.

4. DNS in Cloudflare#

You'll need to setup a Cloudflare account. This is how we handle changing public IPs that are out of our control. Add your domain, the free tier is fine. Then add 1 A record pointing at your public IP. CNAMEs for any subdomains, for now, jellyfin and blog should be sufficient:

  • Type: A, Name: colekujawa.com, Content: <your public IP>, Proxy status: DNS only (grey cloud)
  • Type: CNAME, Name: blog, Content: colekujawa.com, Proxy status: DNS only
  • Type: CNAME, Name: jellyfin, Content: colekujawa.com, Proxy status: DNS only

Keep the cloud grey, set to "DNS only". If you switch on Cloudflare's orange-cloud proxy, Cloudflare terminates SSL at its edge, and the reverse proxy on your server can no longer manage its own certificates through Let's Encrypt. The full chain you want is:

1visitor -> Cloudflare DNS -> your public IP -> router (forwards 80/443) -> host firewall (route-allow to 172.16.0.253) -> nginx-proxy-manager -> container

Keeping the IP current: cloudflare-ddns#

A home connection gets a new public IP whenever the ISP decides to hand one out, I've had ISPs that never changed it in years, I have one now that changes it almost weekly. The cloudflare-ddns container checks your current IP on a schedule and updates the Cloudflare records when it changes. DOMAINS only needs your apex domain: blog and jellyfin are CNAMEs pointing at it, so keeping the apex A record current moves all of them. (favonia/cloudflare-ddns only manages A and AAAA records anyway, never CNAMEs. It takes a comma-separated list if you own several apex domains.) Here is its definition; it drops into the compose file with the rest:

1 cloudflare-ddns:
2 image: favonia/cloudflare-ddns:latest
3 container_name: cloudflare-ddns
4 restart: always
5 environment:
6 - CLOUDFLARE_API_TOKEN=${CF_TOKEN}
7 - DOMAINS=colekujawa.com # apex only; the subdomains are CNAMEs to this
8 - PROXIED=false
9 - IP6_PROVIDER=none

Create the token in Cloudflare: your profile icon (top right) → API Tokens → Create Token → Create Custom Token. Give it two permissions, Zone > DNS > Edit and Zone > Zone > Read, and scope it to just this zone, not all zones. Copy it the moment it's generated, Cloudflare only shows it once. That value is what goes into your homelab .env as CF_TOKEN=.

PROXIED=false keeps the records grey to match the section above. I run one of these per apex domain so their logs don't interfere with each other.

5. The Container Stack#

What we're designing here is a Docker Compose stack, which has it's own bridge network. Mine is called smart-tilde, on 172.16.0.0/24. Containers on that network reach each other by container name, jellyfin:8096 or payloadcms-app:3000, over the bridge. Docker networking handles the name resolution and routing. The reverse proxy sits on the same network with a fixed address, 172.16.0.253, because the firewall route rules from section 3 point at that IP. It is the only container the internet can reach.

The flow for jellyfin.colekujawa.com is:

1:443 on the host -> UFW route-allow -> nginx-proxy-manager (172.16.0.253) -> jellyfin:8096 (over the smart-tilde network)

Jellyfin publishes port 8096, which makes it reachable from your LAN, handy for setup, but there is no route rule for it, so the internet cannot see it. To put it online you add a proxy host in nginx-proxy-manager and the traffic rides in on the 443 rule you already have. A service that needs a raw port instead of HTTPS proxying, like game servers, will need its own ufw route allow on top.

How I lay out a project#

Everything for one stack lives in one directory. On my server that is ~/projects/homelab/:

1homelab/
2 docker-compose.yaml
3 .env # secrets, never committed
4 data/
5 npm/
6 heimdall/
7 jellyfin/
8 ...

The data/ directory is a convention of mine, not a Docker feature. One subdirectory per container, bind-mounted into that container wherever its config and state live, extensible to whatever files you want available on the host:

1volumes:
2 - ./data/jellyfin/config:/config
3 - ./data/jellyfin/cache:/cache

The left of each : is a path on the host, the right is a path inside the container, and Docker keeps the two as one live directory. So Jellyfin's settings, users, and artwork sit in ./data/jellyfin/config/ on the host, where I can read them, edit them, grep them, and back them up, without ever exec-ing into the container. Delete and recreate the container and that config is untouched.

Add :ro to make a mount read-only, which is how the monitoring containers reach host files they should only ever look at:

1volumes:
2 - /proc:/host/proc:ro
3 - /sys:/host/sys:ro

Two kinds of thing do not get a data/ directory:

  • Secrets go in .env as KEY=value and are referenced in the compose file as ${KEY}. Keep .env out of version control.
  • Databases use named Docker volumes (payloadcms_db_data: in the PayloadCMS file below), not bind mounts. You never hand-edit a database's files, so you let Docker manage them. Bind-mount the things you want to touch; leave the rest to Docker.

Because the containers run as UID 1000, your user (that is what the PUID and PGID lines in the compose file below do), everything they write into data/ is owned by you. No sudo, no chown afterward. This is why section 1 said to make your account the first one on the machine.

Open the project in VS Code#

Make the directory and open it.

1mkdir -p ~/projects/homelab && cd ~/projects/homelab
2code .

A word on what that costs. Remote-SSH is not a thin client: on connect, VS Code runs a full Node server on the host that does the file watching, language services, and extensions, so your PC only draws the UI. That server's file watcher recursively walks the entire open folder. Open ~/projects/homelab and it is a non-event. Open your home directory, or /, or /srv once media is mounted there, and the walk hits terabytes and pegs every core; the first time I did that it took the box down for ten minutes.

Once your data dirs start to fill up you may want to add additional limits to what VS Code scans.

How to read the compose file#

If you haven't read one before, five things carry most of the meaning:

  • ports: - 82:80 left is the port on the host, right is the port inside the container. Heimdall serves on 80 internally; you reach it on :82 because you set the left number to something free. Only the left number ever changes.
  • networks: plain membership ([smart-tilde]) puts the container on the bridge so others reach it by name. ipv4_address: pins it to a fixed address, which you only do for the handful the firewall rules name by IP.
  • depends_on: … condition: service_healthy don't start this container until that one's healthcheck passes. Used below so the app never starts before its database is actually accepting connections, not just running.
  • volumes: - ./data/x:/config vs a named volume like payloadcms_db_data: the first is a real folder on the host you can open and back up; the second is storage Docker manages for you, for things you never hand-edit (databases).
  • ${CF_TOKEN} filled in from .env when you run docker compose up. The file itself stays free of secrets and safe to commit.

The Compose File#

A trimmed core stack. Save it as docker-compose.yaml in that project directory:

1networks:
2 smart-tilde:
3 name: smart-tilde
4 driver: bridge
5 ipam:
6 config:
7 - subnet: 172.16.0.0/24
8
9services:
10 # only container the internet can reach, via the route rules in section 3
11 nginx-proxy-manager:
12 image: jc21/nginx-proxy-manager:latest
13 container_name: nginx-proxy-manager
14 restart: unless-stopped
15 networks:
16 smart-tilde:
17 ipv4_address: 172.16.0.253 # firewall route rules point here
18 ports:
19 - 80:80 # public HTTP (redirects to HTTPS)
20 - 443:443 # public HTTPS
21 - 127.0.0.1:81:81 # admin UI, localhost only, reach it over an SSH tunnel
22 volumes:
23 - ./data/npm/data:/data
24 - ./data/npm/letsencrypt:/etc/letsencrypt
25
26 # Docker API gateway, so nothing else has to mount the raw socket
27 socket-proxy:
28 image: lscr.io/linuxserver/socket-proxy:latest
29 container_name: socket-proxy
30 restart: always
31 labels:
32 - com.centurylinklabs.watchtower.enable=false # Watchtower must never update this one
33 networks:
34 smart-tilde:
35 ipv4_address: 172.16.0.254
36 volumes:
37 - /var/run/docker.sock:/var/run/docker.sock:ro
38 environment:
39 - CONTAINERS=1
40 - IMAGES=1
41 - NETWORKS=1
42 - SERVICES=1
43 - TASKS=1
44 - INFO=1
45 - EVENTS=1
46 - PING=1
47 - VERSION=1
48 - VOLUMES=1 # Portainer lists volumes
49 - POST=1 # allow write operations at all
50 - CONTAINERS_CREATE=1 # Portainer stacks / Watchtower replacing a container
51 - CONTAINERS_START=1
52 - CONTAINERS_UPDATE=1
53 - CONTAINERS_DELETE=1 # Portainer stack removal / Watchtower cleanup
54 - IMAGES_DELETE=1 # Watchtower removing the old image after an update
55 - AUTH=0
56 - SECRETS=0
57 - EXEC=0
58 - SWARM=0
59 - SYSTEM=0
60 - BUILD=0
61 - COMMIT=0
62
63 # monitoring; these publish ports but get no route rule, so LAN-only
64 heimdall:
65 image: lscr.io/linuxserver/heimdall:latest
66 container_name: heimdall
67 restart: unless-stopped
68 networks: [smart-tilde]
69 environment: [PUID=1000, PGID=1000, TZ=America/New_York]
70 ports:
71 - 82:80
72 volumes:
73 - ./data/heimdall:/config
74
75 portainer:
76 image: portainer/portainer-ce:latest
77 container_name: portainer
78 restart: unless-stopped
79 command: -H tcp://socket-proxy:2375 # via the proxy, not the socket
80 networks: [smart-tilde]
81 ports:
82 - 9000:9000
83 volumes:
84 - ./data/portainer:/data
85
86 dozzle:
87 image: amir20/dozzle:latest
88 container_name: dozzle
89 restart: unless-stopped
90 networks: [smart-tilde]
91 ports:
92 - 8081:8080
93 environment:
94 DOZZLE_FILTER: "status=running"
95 DOCKER_HOST: tcp://socket-proxy:2375
96
97 netdata:
98 image: netdata/netdata:latest
99 container_name: netdata
100 restart: unless-stopped
101 hostname: home-server
102 networks: [smart-tilde]
103 ports:
104 - 19999:19999
105 cap_add: [SYS_PTRACE] # read other processes' details
106 security_opt: [apparmor:unconfined] # read /proc and /sys for every process
107 environment:
108 DOCKER_HOST: tcp://socket-proxy:2375
109 volumes:
110 - ./data/netdata:/etc/netdata
111 - /proc:/host/proc:ro
112 - /sys:/host/sys:ro
113
114 # automation
115 watchtower:
116 image: ghcr.io/nicholas-fedor/watchtower:latest
117 container_name: watchtower
118 restart: unless-stopped
119 networks: [smart-tilde]
120 environment:
121 WATCHTOWER_CLEANUP: "true"
122 WATCHTOWER_SCHEDULE: "0 30 4 * * *" # 4:30am daily
123 DOCKER_HOST: tcp://socket-proxy:2375
124
125 cloudflare-ddns:
126 image: favonia/cloudflare-ddns:latest
127 container_name: cloudflare-ddns
128 restart: always
129 environment:
130 - CLOUDFLARE_API_TOKEN=${CF_TOKEN}
131 - DOMAINS=colekujawa.com # apex only; subdomains are CNAMEs to this
132 - PROXIED=false
133 - IP6_PROVIDER=none
134
135 # content
136 jellyfin:
137 image: jellyfin/jellyfin:latest
138 container_name: jellyfin
139 restart: unless-stopped
140 networks: [smart-tilde]
141 environment: [PUID=1000, PGID=1000, TZ=America/New_York]
142 ports:
143 - 8096:8096
144 volumes:
145 - ./data/jellyfin/config:/config
146 - ./data/jellyfin/cache:/cache
147 - /srv/media/movies:/data/movies:ro
148 - /srv/media/tvshows:/data/tvshows:ro

A note on forked images. containrrr/watchtower and oznu/cloudflare-ddns are the names a lot of older tutorial uses, and both are archived, no upstream, no fixes. I run the maintained forks, nicholas-fedor/watchtower and favonia/cloudflare-ddns.

A note on restart:. Most services here use unless-stopped: come back after a crash or a reboot, but stay down if I stopped them on purpose. A couple use always, which also restarts them after a manual stop once Docker itself restarts. That's for things you never want left off: socket-proxy, because everything else reaches Docker through it, and cloudflare-ddns, because there's no reason to ever have DNS updates switched off. Neither policy brings back a container that another program stopped through the Docker API mid-run, only a Docker restart does. That's the trap in the socket-proxy note below.

Put your secrets in a .env file next to the compose file, one KEY=value per line, and keep it out of version control:

1# homelab/.env
2CF_TOKEN=your-cloudflare-api-token-from-section-4

Just the one line for this trimmed stack, more services usually just means more lines here.

Start the stack:

1docker compose up -d
2docker compose ps

The monitoring UIs are on the LAN (http://server-ip:9000 for Portainer, :19999 for Netdata, :8081 for Dozzle, :82 for Heimdall). The NPM admin page is bound to localhost only, so reach it over an SSH tunnel:

1ssh -p 1021 -L 8181:localhost:81 you@192.168.0.161
2# then open http://localhost:8181 on your laptop

Once the proxy is configured you can put any of these behind a subdomain with a certificate, and add access control in front, which is Part 2.

About socket-proxy#

Portainer, Dozzle, Netdata, and Watchtower all need the Docker API to do their jobs. The quick option is to bind-mount /var/run/docker.sock into each of them, but that socket is root on the host, and any container that has it can start a privileged container and take over the machine. socket-proxy mounts the socket once, in one small container, and exposes a filtered TCP API where each capability is switched on or off with an environment variable. I allow the read endpoints, POST, and the specific CONTAINERS_CREATE / START / UPDATE / DELETE and IMAGES_DELETE flags Watchtower and Portainer need to actually act on containers, since on this image POST on its own is not enough. I deny EXEC, SECRETS, and the Swarm endpoints. Every other container points at tcp://socket-proxy:2375 and never sees the real socket.

One cron. Since Watchtower talks to Docker through socket-proxy, if Watchtower ever stops socket-proxy to update it, it kills its own connection mid-operation and leaves a pile of containers stopped and not recreated. A stopped-by-API container does not come back on its own, restart: unless-stopped or not. That is why socket-proxy carries the com.centurylinklabs.watchtower.enable=false label above. I update it out of band instead, a small weekly cron that pulls and recreates just that one container.

The same label matters more widely. Watchtower updates every container it can see, across all your compose projects, not just this stack. That is what you want for stateless services and it can be a real hazard for stateful ones: a database that jumps a major version overnight can end up with data it can no longer read. Put com.centurylinklabs.watchtower.enable=false on anything with a volume you care about, and pin those images to a major version rather than latest.

nginx-proxy-manager: the first proxy host#

Go to the admin UI on port 81 (192.168.0.161:81) and log in. The default credentials are admin@example.com and changeme; change both right away. Then add a Proxy Host:

  • Domain Names: jellyfin.colekujawa.com
  • Scheme: http
  • Forward Hostname / IP: jellyfin (the container name since the proxy manager and jellyfin are containers on the same docker network)
  • Forward Port: 8096
  • Block Common Exploits: on
  • Websockets Support: on
  • SSL tab: request a new Let's Encrypt certificate using a DNS Challenge, DNS Provider Cloudflare, and paste the same Cloudflare API Token from section 4 into the credentials field, then turn on Force SSL, HTTP/2, and HSTS

NPM requests the certificate over a DNS-01 challenge against Cloudflare instead of the usual HTTP-01 on port 80, more reliable, since it doesn't depend on port 80 being reachable from the internet (some ISPs block or CGNAT it). It auto-renews 30 days before expiry. Save it, and https://jellyfin.colekujawa.com is live with a valid certificate, with only ports 80 and 443 open on the house. Backend traffic from NPM to the container is plain HTTP over the private network, which is fine because that network never leaves the host.

Confirm it from outside your own network, since a LAN test passes even when the router forward is wrong. Load the URL on your phone over mobile data, or from the host:

1curl -s https://api.ipify.org; echo # your current public IP
2curl -sI https://jellyfin.colekujawa.com # headers back, not a hang

Heimdall: one shortcut to reach them all#

Heimdall's already running from section 5's compose file, but it's an empty dashboard until you add shortcuts. Once NPM, Portainer, Dozzle, Netdata, and Jellyfin are live, this is the one page worth bookmarking, everything else is a click from here.

At http://192.168.0.161:82, click Application list in the left rail, then Add. The Application Type dropdown does the real work: pick a match, hundreds of self-hosted apps are already in there, including everything in this stack, and it fills in the icon, description, and color for you.

Fill in Application name and URL, leave Colour alone, and skip the Config (Optional) section unless you want live stats on the tile, it needs separate API credentials per app and isn't worth it for a first pass. One thing to know if you do use it: picking an Application Type you already have another item of pre-fills Config with that item's saved credentials. Worth checking before you hit Save.

Repeat for whatever's running:

  • Portainer — Application Type Portainer — http://192.168.0.161:9000
  • Dozzle — Application Type Dozzle — http://192.168.0.161:8081
  • Netdata — Application Type Netdata — http://192.168.0.161:19999
  • Nginx Proxy Manager — Application Type Nginx Proxy Manager — http://192.168.0.161:81
  • Jellyfin — Application Type Jellyfin — https://jellyfin.colekujawa.com

That's the home page. Bookmark http://192.168.0.161:82 and everything else in this stack is one click away.

The blog: PayloadCMS as its own project#

I keep the website in its own compose project, separate from the infrastructure stack. It has a different release cycle and its own repository, and I don't want a docker compose down on one to touch the other. The thing in the build: context is my PayloadCMS setup; any web container that serves HTTP on a port slots in the same way. What matters is the wiring: the two projects connect because the website joins the same smart-tilde network, declared as external.

1services:
2 payloadcms-app:
3 build:
4 context: ./data/payloadcms
5 dockerfile: Dockerfile
6 container_name: payloadcms-app
7 restart: unless-stopped
8 networks:
9 - payloadcms # private: app to its own database
10 - smart-tilde # shared: so the proxy can reach it
11 depends_on:
12 payloadcms-db:
13 condition: service_healthy
14 env_file: [.env]
15 environment:
16 - NEXT_PUBLIC_SERVER_URL=https://blog.colekujawa.com
17 - PAYLOAD_SECRET=${PAYLOAD_SECRET}
18 - DATABASE_URI=mongodb://payloadcms-db/payloadcms
19
20 payloadcms-db:
21 image: mongo:7 # pin a major version; :latest on a database invites a breaking upgrade
22 container_name: payloadcms-db
23 restart: unless-stopped
24 networks: [payloadcms] # not on smart-tilde, nothing outside needs it
25 labels:
26 - com.centurylinklabs.watchtower.enable=false # never auto-update a database
27 volumes:
28 - payloadcms_db_data:/data/db
29 healthcheck:
30 test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
31 interval: 30s
32 timeout: 10s
33 retries: 3
34
35networks:
36 payloadcms:
37 name: payloadcms
38 smart-tilde:
39 external: true
40 name: smart-tilde
41
42volumes:
43 payloadcms_db_data:

This project gets its own .env too, in its own directory, separate from the homelab one:

1# payloadcms/.env
2PAYLOAD_SECRET=<a long random string, e.g. from `openssl rand -base64 32`>

Two things worth understanding, not just copying. PAYLOAD_SECRET signs PayloadCMS's auth cookies and JWTs, treat it like a password: long, random, never reused, never committed. And NEXT_PUBLIC_SERVER_URL above isn't decorative, PayloadCMS builds its CORS allowlist directly from it, and only it, this trimmed example allows exactly one origin. Set it to anything other than the exact public HTTPS URL your domain resolves to and the admin panel's own API calls get rejected by the browser, live preview breaks, asset URLs point at the wrong place. It has to match, protocol included, before you touch anything else. (DATABASE_URI and NEXT_PUBLIC_SERVER_URL are hardcoded above rather than pulled from .env, they're not exactly secret, only PAYLOAD_SECRET needs to stay out of the compose file.)

The database is on the payloadcms network only, so the reverse proxy cannot see it and neither can anything else except the app. The app is on both networks. Add one more proxy host in nginx-proxy-manager, blog.colekujawa.com to payloadcms-app:3000, with Let's Encrypt and Force SSL (and point the bare colekujawa.com at the same place, or add a redirect from it). That is the blog this post is published on. This is the hub-and-spoke pattern I use for every project that needs to be online: the app joins the hub network, the database never does.

This is what I meant about light rules for routing into the Docker network. The whole internet-facing surface is two ports at the router, two ufw route allow lines, and one reverse proxy. Adding a service means starting its container on smart-tilde, adding an A record, and filling in a proxy host form. Removing one is the same steps in reverse.

Where that leaves you#

A server on the public internet where:

  • the host firewall denies everything inbound and everything forwarded by default
  • SSH is reachable from your LAN only, on a non-standard port, key auth only
  • the router forwards only 80 and 443, and each one is paired with a single firewall route rule to the reverse proxy
  • one container is internet-facing; every other service publishes its port to the LAN only, with no route rule
  • the Docker socket sits behind a filtered gateway instead of being mounted into four containers, and Watchtower is blocked from touching that gateway
  • DNS points home and corrects itself when your ISP changes your IP
  • you can see what is running, with Portainer for containers, Dozzle for logs, and Netdata for the host
  • updates mostly take care of themselves, through Ubuntu Pro and unattended-upgrades on the host and Watchtower for the containers
  • you are serving real content, a Jellyfin library and a blog, both on your own domain with valid certificates

It is a boring setup. On a normal week it needs nothing from you, and that is the whole idea.