Skip to content

VPS

How to run apps with Docker Compose on a VPS

Install Docker on Ubuntu, run an app with PostgreSQL behind Caddy with automatic HTTPS, and avoid the firewall gotcha that exposes your database.

Docker Compose is one of the easiest ways to run a real application on a VPS. Instead of installing a runtime, a database and a web server by hand, you describe them in one file and start the whole stack with a single command. Moving to a new server later means copying that file and your data, not repeating an afternoon of setup. This guide walks through a complete, production-style setup on Ubuntu: Docker from the official repository, an app with PostgreSQL, persistent volumes, a Caddy reverse proxy with automatic HTTPS, logs, updates, and the firewall gotcha that catches almost everyone.

What you need

  • A VPS running a current Ubuntu LTS release with root or sudo access. A small plan is fine for one app and a database; give PostgreSQL more RAM as your data grows.
  • A domain name with an A record pointing at your server's IPv4 address (and an AAAA record for IPv6 if you want it). Caddy needs this to get a certificate.
  • An app that is available as a container image, or a Dockerfile you can build.

Before you start, update the system with sudo apt update && sudo apt upgrade and make sure you can log in with an SSH key.

Step 1: install Docker from the official repository

Ubuntu's own docker.io package works, but it often lags behind and ships Compose separately (or as the old docker-compose v1 with a hyphen). Docker's own apt repository gives you the current Engine plus the Compose v2 plugin, which you run as docker compose. If you installed docker.io or docker-compose before, remove them first with sudo apt remove docker.io docker-compose.

sudo apt-get update
sudo apt-get install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Check that it works:

sudo docker run --rm hello-world
docker compose version

To run Docker without sudo, add your user to the docker group with sudo usermod -aG docker $USER and log in again. Be aware that membership of this group is effectively root access, so only add accounts you trust. The Docker service starts at boot automatically.

Step 2: lay out the project

Keep each stack in its own directory. Compose uses the directory name as the project name, which prefixes container, network and volume names.

/opt/myapp/
  compose.yaml
  .env
  Caddyfile

Put secrets in .env, next to compose.yaml. Compose reads it automatically for variable substitution, and you can pass it into containers with env_file. Lock it down with chmod 600 .env, and never commit it to git.

POSTGRES_USER=myapp
POSTGRES_PASSWORD=change-me-to-a-long-random-string
POSTGRES_DB=myapp

Step 3: write compose.yaml

This example runs a web app listening on port 3000, PostgreSQL, and Caddy in front of both. Replace the app image with your own.

services:
  app:
    image: ghcr.io/example/myapp:1.4.2
    restart: unless-stopped
    environment:
      DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:17
    restart: unless-stopped
    env_file: .env
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5

  caddy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
      - "443:443/udp"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - app

volumes:
  db_data:
  caddy_data:
  caddy_config:

A few things worth noticing:

  • Only Caddy publishes ports. The app and database have no ports: section, so they are reachable only on the private network Compose creates for the project. Caddy reaches the app by its service name, app, and the app reaches the database at db:5432.
  • Pin image versions. postgres:17 and a specific app tag mean an update never surprises you with a new major version. PostgreSQL in particular cannot read a data directory from a different major version without a proper upgrade.
  • The healthcheck plus condition: service_healthy makes Compose wait until PostgreSQL accepts connections before starting the app, which avoids crash loops on boot. The doubled $$ stops Compose from substituting the variable itself, so the shell inside the container does it.

Volumes: where your data lives

Containers are disposable. Anything written inside a container is lost when it is recreated, which happens on every update. Named volumes such as db_data are stored by Docker under /var/lib/docker/volumes/ and survive docker compose down, image updates and reboots. Bind mounts like ./Caddyfile map a file or folder from the host, which is handy for config you want to edit directly.

Two volumes matter most here: db_data holds your database, and caddy_data holds your TLS certificates and keys. Losing caddy_data forces Caddy to request new certificates, and doing that repeatedly can hit Let's Encrypt rate limits. Note that docker compose down -v deletes named volumes, so leave the -v off unless you really mean it.

Restart policies

PolicyBehaviourUse it for
noNever restarts (the default)One-off tasks
on-failureRestarts only after a non-zero exitJobs that should stop cleanly when done
alwaysAlways restarts; a container you stopped by hand comes back when the Docker daemon restartsRarely the best choice
unless-stoppedRestarts after crashes and reboots, but stays stopped if you stopped itMost long-running services

With unless-stopped, your stack comes back by itself after a crash or a server reboot. No systemd unit is needed.

Step 4: Caddy and automatic HTTPS

Caddy is a web server that obtains and renews TLS certificates on its own. The whole config for one site is three lines:

app.example.com {
    reverse_proxy app:3000
}

When Caddy starts, it sees a public hostname, requests a certificate from Let's Encrypt over port 80 or 443, redirects HTTP to HTTPS, and renews before expiry. For that to work, the DNS record must already point at the server and ports 80 and 443 must be open. Port 443 over UDP is for HTTP/3 and is optional. To host more sites, add more blocks to the Caddyfile, each pointing at a different service.

Start the stack:

cd /opt/myapp
docker compose up -d
docker compose ps

Visit your domain and you should get the app over HTTPS. If not, docker compose logs caddy will usually tell you why, most often a DNS record that has not propagated yet or a blocked port. After editing the Caddyfile, apply it with docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile.

Step 5: logs

Every container's output is captured by Docker. Compose lets you read it per service:

docker compose logs -f app          # follow one service
docker compose logs --tail 100 db   # last 100 lines
docker compose logs --since 30m     # everything from the last 30 minutes

By default Docker uses the json-file log driver with no size limit, so a chatty app can slowly fill your disk. Set a global limit in /etc/docker/daemon.json:

{
  "log-driver": "local",
  "log-opts": {
    "max-size": "10m",
    "max-file": "5"
  }
}

Restart Docker with sudo systemctl restart docker. The new settings apply to containers created afterwards, so run docker compose up -d --force-recreate to pick them up. Use docker system df now and then to see how much space images, containers and volumes use.

Step 6: updating images

To update, change the tag in compose.yaml if you pinned one, then pull and recreate:

cd /opt/myapp
docker compose pull
docker compose up -d
docker image prune -f

up -d only recreates containers whose image or config changed, and the volumes stay attached, so your data is untouched. The final command removes old images that are no longer used. Read the release notes before a major version bump, especially for databases. Upgrading PostgreSQL from 17 to 18, for example, needs a dump and restore or pg_upgrade, not just a new tag.

Back up the database properly

Copying the files of a running database can give you a corrupt backup. Use pg_dump instead, and run it from cron every night:

docker compose exec -T db pg_dump -U myapp myapp | gzip > /root/backups/myapp-$(date +%F).sql.gz

Keep a copy somewhere other than the VPS itself. Zettako VPS plans include free daily backups, but your own dumps let you restore a single database to a specific day without restoring the whole server.

The gotcha: Docker bypasses ufw

This is the mistake that exposes databases to the internet. You enable ufw, allow only SSH, 80 and 443, and assume everything else is blocked. Then you add ports: - "5432:5432" to the database so you can connect from your laptop, and PostgreSQL is now open to the entire internet, firewall or not.

The reason is that Docker manages its own iptables rules. Traffic to a published port is redirected to the container in the NAT table and then passes through the FORWARD chain, while ufw's rules for incoming traffic sit in the INPUT chain. The packets never reach ufw's rules, and ufw status gives no hint that anything is open.

How to stay safe:

  1. Do not publish ports you do not need. Services on the same Compose network talk to each other by name without any ports: entry. In the example above, only Caddy is reachable from outside.
  2. Bind admin ports to localhost. If you need to reach the database from the host, publish it on the loopback address only:
      db:
        ports:
          - "127.0.0.1:5432:5432"
    Then connect from your own machine through an SSH tunnel: ssh -L 5432:127.0.0.1:5432 user@your-server.
  3. Use the DOCKER-USER chain for advanced rules. Docker leaves this iptables chain alone and evaluates it before its own forwarding rules, so it is the right place to restrict published ports to certain source IPs.
  4. Check from outside. Run nmap -p- your-server-ip from another machine to see what is really reachable.

Still enable ufw for everything that is not Docker, starting with SSH:

sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443
sudo ufw enable

Allow OpenSSH before enabling ufw, or you can lock yourself out of the server.

Everyday commands

CommandWhat it does
docker compose up -dCreate or update the stack and start it in the background
docker compose psList the stack's containers and their health
docker compose restart appRestart one service
docker compose exec app shOpen a shell inside a running container
docker compose downStop and remove containers and networks, keep volumes
docker compose configPrint the final config with variables filled in, useful for spotting typos

Where to run it

Compose needs a server where you have root access and can install Docker, which shared hosting and managed panels do not allow. A Zettako VPS gives you full root access, NVMe storage, a dedicated IPv4 address plus a /64 IPv6 subnet, DDoS protection and free daily backups, in our Frankfurt datacenter. That is everything this guide uses, and when your stack needs more memory or disk, you can upgrade the plan without rebuilding anything.

Ready to deploy your stack?

Get a VPS with full root access, NVMe storage and daily backups, and have Docker running in minutes.

Starting at £9.95GBP/30d