Install a Link Shortener on Linux: Docker, Nginx, and TLS

A pair of hands is connecting network cables to a piece of server hardware in a server room.

Written by

in

To install a link shortener on a Linux server, you set up four things in order: a domain's A record pointing at the box, the shortener application itself (Docker Compose or a native package), a database for links and click events, and a TLS certificate so redirects serve over HTTPS. The order matters more than the tool you choose. The redirect endpoint has to answer quickly and keep a valid certificate; if it doesn't, every branded link you printed stops working.

TL;DR:

  • Pick Docker Compose unless your host forbids a Docker daemon.
  • Point DNS at the server a day early with a 300 second TTL.
  • Terminate TLS at the reverse proxy and automate renewal with a systemd timer.
  • Serve 302 redirects until a destination is final; 301 gets cached and cannot be recalled.
  • Back up the database and the application's key file in the same archive, or protected links break.

Table of Contents

The Four Moving Parts of a Self-Hosted Shortener

A pair of hands installing four distinct physical modules into a structured server enclosure.

Every install, whether you drop a compiled binary onto a box or run a PHP app in a container, comes down to the same four pieces. Skip one and the app looks healthy in a browser tab while failing the moment real traffic arrives.

DNS. A domain or subdomain whose A record (plus an AAAA record if the server has IPv6) points at the machine's IP address. This step gets rushed and takes longest to undo.

TLS. A valid certificate for that hostname. Browsers now treat plain HTTP redirects as suspect, and several chat apps refuse to unfurl them. Let's Encrypt is the default choice: free, automated, and validated by an HTTP-01 challenge that proves you control the domain.

The application and its data store. The shortener itself plus MySQL, MariaDB, PostgreSQL or SQLite. SQLite handles a few hundred thousand links without trouble; past that, concurrent writes start to queue behind a single write lock.

The reverse proxy. Nginx, Apache or Caddy on ports 80 and 443, forwarding to the app on localhost. A shortener reachable directly on port 8080 is an unfinished install.

Order of operations beats tool choice

Do DNS first, then the certificate, then the app, then the links. Reverse that and you can spend an hour debugging an application that was working all along, against a hostname that does not resolve yet.

Two Install Paths, and the One I'd Pick

Containers and distro packages both work. They fail in different ways, which matters more than which one starts faster.

Factor Docker Compose Native package
Time to first redirect 15 to 30 minutes 30 to 60 minutes
Upgrades Change the image tag, run docker compose up -d Package manager plus manual database migrations
Runtime drift None, the image carries its own PHP or Go Pinned by whatever the distro ships
Database Container or external server Usually local MySQL or PostgreSQL
Debugging docker compose logs -f app journalctl -u shortener
Best for Most installs Locked-down hosts with no Docker daemon

I would run Compose on any server I control. The biggest reason for me is reversibility: when an upgrade misbehaves, rolling the image tag back takes ten seconds. Rolling back a distro package that ran a database migration takes a restore from backup. If you are still deciding between owning the stack and renting one, the trade-offs in hosted vs self-hosted link shortener are worth ten minutes before you provision anything.

These steps work on Ubuntu 22.04 and 24.04 and Debian 12. RHEL derivatives need different package names but the same order.

1. Create a service account

Do not run the application as root. A dedicated system user with no shell login limits the blast radius if the app is compromised.

sudo adduser --system --group --home /opt/shortener shortener

2. Install the container runtime

Use Docker's own repository rather than the distro package, which trails the release and in older repos still ships Compose v1. Docker's Compose documentation lists the per-distro steps. Then confirm the plugin: docker compose version should print v2.x. If it prints a hyphenated v1 string, you have the legacy binary.

3. Bring up the app and its database

A working compose file does three jobs: run the app, run the database, and persist both.

services:
  app:
    image: <the image your vendor publishes>
    restart: unless-stopped
    env_file: .env
    ports:
      - "127.0.0.1:8080:8080"
  db:
    image: mariadb:11
    restart: unless-stopped
    volumes:
      - db:/var/lib/mysql
    environment:
      MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
volumes:
  db:

The 127.0.0.1: prefix in the port mapping is the line that matters. It binds the app to loopback so only the reverse proxy reaches it. Drop that prefix and you have published an unauthenticated admin panel to the open internet.

4. Add the reverse proxy blocks

Nginx needs two server blocks: port 80 to answer the ACME challenge and push everything else to HTTPS, port 443 to proxy the app. The Nginx return directive handles the first one without a rewrite regex.

server {
    listen 80;
    server_name sho.rt;
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://$host$request_uri; }
}

5. Issue the certificate

Run sudo certbot --nginx -d sho.rt, then sudo certbot renew --dry-run to confirm the renewal timer is installed and working. A failed dry run means the next expiry will take the links down.

6. Open two ports and keep the third

sudo ufw allow 80,443/tcp first. Allow SSH before running sudo ufw enable, or you lock yourself out of the box and finish the install through a provider console. Ubuntu's community firewall guide covers the ordering.

7. Reboot and retest

sudo reboot, wait ninety seconds, then curl -I https://sho.rt/abc123. Containers set to restart: unless-stopped come back on their own. If a service does not return after a reboot, fix its startup configuration.

DNS and TLS: The Two Things That Break Quietly

Both fail without an error in your application log, so they get separate attention here.

Lower the TTL before you move. Drop the A record's TTL to 300 seconds a full day before cutover. A 3600 second TTL means a mistaken IP address costs you an hour of waiting while the old record drains from resolvers.

Check resolution from outside your network. dig +short sho.rt on the server proves little if your laptop is on the same network. Query a public resolver explicitly: dig @1.1.1.1 sho.rt.

Plan for port 80 being blocked. The HTTP-01 challenge needs port 80 reachable from the internet. If your provider blocks it, switch to the DNS-01 challenge and an API token instead of fighting the firewall.

Let's Encrypt certificates last 90 days. If renewal is not automated, the outage arrives on a date nobody wrote down.

Status Codes and Caching for the Redirect

A link shortener returns an HTTP status code and a Location header. Everything else, the dashboard and the charts, is decoration around that one response. RFC 9110 defines the codes that matter here.

301 and 308 are permanent and cacheable. Browsers and intermediaries store them. Change the destination on the server and returning visitors still land on the old URL, sometimes for months.

302 and 307 are temporary. Use these for campaign links, seasonal pages, and anything you might repoint. 307 preserves the request method; 302 historically did not.

302 is what I would ship as the default. Marketing links get repointed constantly. The cost of a cached 301 is a link you cannot fix without a new short code.

Watch the response time. curl -o /dev/null -s -w "%{time_total}\n" https://sho.rt/abc123 should come back under 0.1 seconds from a nearby region. If click logging writes to the database synchronously before redirecting, that number climbs under load. Asynchronous logging is worth the small risk of losing a click.

A 301 can sit in a browser cache for months. Repoint the destination and every returning visitor still lands on the old page.

Backups, Log Growth, and the Timers Nobody Remembers

The database is small and the click table is not. Two months of traffic on a busy domain can push click events into the millions of rows, which turns a simple backup into a nightly job that runs longer than you expect.

Dump the database on a schedule. mysqldump --single-transaction --routines shortener > /var/backups/shortener-$(date +%F).sql produces a consistent dump without locking writes. Keep thirty days.

Use a systemd timer instead of a cron entry. Timers log to the journal, so a failed backup leaves a trace you can find. A failed cron job leaves no trace.

Set a retention window on click data. If you do not need IP addresses, hash or truncate them at ingest. It shrinks the table and the compliance surface at the same time. Self-hosted analytics explains what you actually own once the data sits on your own disk.

Pro Tip: Back up the application's key file and its environment file in the same archive as the database dump. Password-protected links and encrypted destination URLs depend on that key. Restore the dump alone and every protected link resolves to an error page with nothing in the logs to explain it. Restore to a second machine once and confirm a protected link still works before you trust the backup.

Hardening the Box Without Breaking the Redirect

Most of the work is closing access paths you did not know were open.

Bind the admin panel to an allowlist. Nginx allow 203.0.113.4; deny all; on the /admin location keeps the dashboard off the public internet without a VPN.

Rate limit the redirect route carefully. A link that goes viral legitimately produces hundreds of requests a second. Set limit_req high enough for real traffic and low enough to blunt scraping.

Keep the app user unprivileged. In Compose, add user: "1000:1000" or the vendor's documented UID. A container running as root inside a shared kernel is a smaller problem than one mounting the host filesystem, but both carry risk.

Turn off self-registration. If the app ships with an open signup screen, disable it. Public shorteners attract abuse and that abuse damages your domain's reputation.

What the Install Actually Costs in Money and Hours

Line item Typical cost
VPS (2 vCPU, 2 GB RAM) $5 to $12 a month
Domain $10 to $15 a year
TLS certificate $0 with Let's Encrypt
First install, from scratch 1 to 3 hours
Install with a one-command installer 15 to 30 minutes

Run the arithmetic over three years. A hosted plan billed at $29 a month costs $1,044. The same period on a $6 VPS is $216, plus a domain and your install time. The savings are real; the maintenance is also real. Someone has to patch the container, watch the backup job, and renew the certificate. If that person does not exist in your company, a hosted plan is the honest answer, and the subscription exit only works when you have budgeted the hours alongside the license.

Skip the Assembly Line: A Shortener That Installs in One Command

Everything above describes the general case: pick an image, write a compose file, wire up the proxy, run certbot, test the reboot. Kortli packages that work into a single installer you run on your own server, then hands you the redirect endpoint, the database schema and the admin panel without those steps. Links live on your domain with no per-domain fee, password protection and A/B split testing are built in, QR codes carry your logo, and click analytics including geographic data stay on your machine rather than someone else's dashboard. It is a one-time license instead of a recurring bill, priced on the site.

The honest caveat: it is still your server. You supply the VPS, the domain and the DNS record, you keep the TLS certificate renewing, and you own the backups. If you would rather not run a database at all, or you have nobody who will check a backup job once a month, a hosted shortener is the better choice. Read the spec sheet before you buy, ours included, and confirm the install path matches the OS version you actually run.

Frequently Asked Questions

A first install from scratch takes roughly one to three hours if you are writing the compose file, Nginx blocks and certificate commands yourself. With a vendor installer the same job runs 15 to 30 minutes. The variable is DNS: a low TTL set a day ahead removes most of the waiting.

No. Most shorteners also ship as a native package or a standalone binary you run behind Nginx or Apache. Docker makes upgrades and rollbacks easier, so I would choose it on any server where you control the daemon. Locked-down hosts without Docker do fine with the native path.

The two usual causes are an expired TLS certificate and a cached 301 pointing at a destination you changed. Automate renewal with a systemd timer and confirm it with certbot renew --dry-run. Serve 302 responses for any link you might repoint, because a cached permanent redirect cannot be recalled from the server side.

Open 80 and 443 to the internet and nothing else. The application itself should listen on loopback, reached only through the reverse proxy. Port 80 stays open for the ACME challenge and the HTTP to HTTPS redirect. Allow SSH before you enable the firewall or you will lock yourself out.

Can I keep click analytics private with a self-hosted shortener?

Yes, and that is one of the main reasons to run one. Click events land in a database on your own server instead of a vendor's. Decide a retention window before launch and hash or truncate IP addresses at ingest if you do not need them.

What should I back up besides the database?

The application's key file and its environment file, in the same archive as the database dump. Password-protected links and encrypted destination URLs are unreadable without that key. Restore the whole set to a second machine once and verify a protected link still resolves.

Sources

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *