Last active 1 month ago

Revision be0683f91caba0b96ddcbaabcd241bc184ce4009

bookwrym-cf.md Raw

BookWyrm + Cloudflare Tunnel

The problem is still that your tunnel is pointing directly at Gunicorn, which doesn't serve static files. It returns HTML for every /static/ request, and the browser blocks it due to MIME type mismatch.

The fix is to add a small nginx container that sits between the tunnel and Gunicorn. nginx serves /static/ and /images/ straight from the Docker volumes, and passes everything else to Gunicorn.

How the traffic flows (i think)

Without the fix:

Cloudflare → cloudflared → bookwyrm-web:8000 (Gunicorn) ✗

With the fix:

Cloudflare → cloudflared → bookwyrm-nginx:80 → /static/ served directly
                                              → everything else → Gunicorn

1. Add the nginx config

Create nginx-books/nginx.conf next to your docker-compose.yml:

upstream bookwyrm {
    server bookwyrm-web:8000;
}

server {
    listen 80;
    client_max_body_size 10M;

    location /static/ {
        alias /app/static/;
    }

    location /images/ {
        alias /app/images/;
    }

    location / {
        proxy_pass http://bookwyrm;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto https;
        proxy_redirect off;
    }
}

2. Add the nginx service to docker-compose.yml

bookwyrm-nginx:
  image: nginx:alpine
  restart: unless-stopped
  depends_on:
    - bookwyrm-web
  volumes:
    - ./nginx-books/nginx.conf:/etc/nginx/conf.d/default.conf:ro
    - bookwyrm_static:/app/static:ro
    - bookwyrm_media:/app/images:ro

Make sure it's on the same Docker network as your other BookWyrm containers.

3. Update your Cloudflare Tunnel to point at nginx

In your cloudflared config (config.yml), change the BookWyrm hostname to route to nginx instead of Gunicorn:

ingress:
  - hostname: books.yourdomain.com
    service: http://bookwyrm-nginx:80   # was bookwyrm-web:8000
  - service: http_status:404

If you manage your tunnel through the Cloudflare dashboard instead of a config file, go to Zero Trust → Networks → Tunnels, edit the tunnel, and change the service URL to http://bookwyrm-nginx:80.

4. Keep USE_HTTPS set to true

Even though TLS is handled by Cloudflare and yr server only speaks plain HTTP internally, BookWyrm still needs to know it's behind HTTPS so it generates correct https:// URLs:

environment:
  USE_HTTPS: "true"

5. Apply the changes

docker compose up -d