Nginx configuration¶
The frontend container is nginx. It serves the Svelte build, proxies /api/ to the backend and /otlp/v1/logs to the collector, and has a second server block that proxies Grafana on its own hostname. The config is frontend/nginx.conf.template.
flowchart LR
Browser -->|"app host :5001"| App["server _"]
Browser -->|"grafana.integr8scode.cc :5001"| G["server grafana.integr8scode.cc"]
App -->|"/api/*"| Backend["${BACKEND_URL}"]
App -->|"/otlp/v1/logs"| Collector["otel-collector:4319"]
App -->|"/grafana"| Redirect["302 to ${GRAFANA_PUBLIC_URL}"]
App -->|"everything else"| Static["static files, SPA fallback"]
G --> Grafana["${GRAFANA_URL}"]
App server¶
server {
listen 5001 ssl;
server_name _;
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
root /usr/share/nginx/html;
index index.html;
Both server blocks listen on 5001 ssl with /etc/nginx/certs/server.crt and server.key. Mount your own pair there and nginx uses it; otherwise a script the image puts in /docker-entrypoint.d/ makes a self-signed pair before nginx starts and keeps it for the container's lifetime. Compose publishes the port as 5001:5001. In production the host's firewall lets only Cloudflare's ranges reach it, so every visitor comes through Cloudflare.
Client addresses and logging¶
# Cloudflare's ranges from https://www.cloudflare.com/ips/; only they may name the visitor's address
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
real_ip_header CF-Connecting-IP;
# A request for a missing file is a 404 in the access log, not an error line
log_not_found off;
limit_req_zone $binary_remote_addr zone=browser_logs:1m rate=30r/m;
Behind Cloudflare every connection comes from a Cloudflare address. set_real_ip_from lists Cloudflare's published ranges, and real_ip_header CF-Connecting-IP makes nginx take the visitor's address from that header on connections from those ranges only. A connection from anywhere else keeps its own address whatever headers it sends. Everything after that sees the visitor: the access log, the browser-log rate limit below, and the X-Real-IP and X-Forwarded-For headers nginx sends upstream. Both carry $remote_addr alone, so an X-Forwarded-For a client made up never reaches the backend's rate limiter. Cloudflare changes the list rarely; cloudflare.com/ips has the current one.
log_not_found off keeps requests for missing files out of the error log; they're still 404s in the access log. Before it, every scanner probing for /wp-includes/ or /firebaseConfig.js wrote an [error] line, and the error-lines alert mailed it.
Security headers¶
# The page's own CSP is a <meta> tag SvelteKit writes into 200.html with hashes of its inline script;
# frame-ancestors only works as a header, so it lives here
add_header Content-Security-Policy "frame-ancestors 'none'";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()";
There are six headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy and Permissions-Policy. Only HSTS has always, so it's the only one nginx also sends on 4xx and 5xx responses.
The page's real CSP isn't here. SvelteKit writes it into 200.html as a <meta> tag with a hash of its inline bootstrap script, from the csp option in vite.config.ts; Frontend build has the policy. A meta CSP can't carry frame-ancestors, so nginx sends just that directive as a header. The browser enforces both.
# A fresh nonce per response for the CSP and the csp-nonce meta tag in 200.html
sub_filter_once off;
sub_filter '**CSP_NONCE**' '$request_id';
The meta CSP allows one nonce for <style> tags, the one CodeMirror puts on its theme. 200.html ships with a **CSP_NONCE** placeholder in the policy and in a csp-nonce meta tag, and sub_filter swaps in $request_id, so every response gets a fresh value. HTML is served with expires -1, so a cached page never reuses an old nonce.
No location block uses add_header. That's on purpose: one add_header inside a location drops every add_header inherited from the server block, so the security headers would disappear from that location. If a location ever needs its own response header, it has to repeat all six. proxy_set_header has the same all-or-nothing inheritance, which is why the SSE location repeats the proxy headers of /api/.
Compression¶
# Enable gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json application/x-font-ttf font/opentype image/svg+xml image/x-icon;
gzip_disable "msie6";
Text types only. Images other than SVG and icons are already compressed.
API proxy and SSE¶
# Resolved per request, so a backend that comes back with a new IP doesn't leave a stale upstream
resolver 127.0.0.11 valid=30s ipv6=off;
set $backend_upstream ${BACKEND_URL};
location /api/ {
proxy_pass $backend_upstream;
# The backend's own certificate, from the volume it writes it to; the SSE location below inherits this
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /etc/nginx/backend/server.crt;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# Forward cookies
proxy_pass_request_headers on;
proxy_set_header Cookie $http_cookie;
# SSE specific settings for /api/v1/events/
location ~ ^/api/v1/events/ {
proxy_pass $backend_upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# Forward cookies
proxy_pass_request_headers on;
proxy_set_header Cookie $http_cookie;
# SSE configuration
proxy_set_header Connection '';
proxy_http_version 1.1;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
The backend's address goes through a variable and Docker's resolver, like Grafana's below, so nginx looks backend up again every 30 seconds. With a plain proxy_pass https://backend:443, nginx resolves it once at startup. A backend that comes back with a new IP, for example after a Docker restart, then gets 502 until the frontend restarts too.
proxy_ssl_verify on checks the backend's certificate on every request. The backend makes that certificate when it first starts and keeps it in the backend_tls_cert volume, nginx mounts the volume read-only, and proxy_ssl_trusted_certificate trusts exactly that file, so a different server answering as backend gets a 502. The frontend waits for the backend's healthcheck, since nginx reads the file only when it starts.
The SSE location under /api/v1/events/ speaks HTTP/1.1 with an empty Connection header, turns off buffering and caching, and raises both timeouts to 24 hours so long-lived streams aren't cut after the default 60 seconds. proxy_buffering off alone is enough to pass each event through as it arrives.
Browser logs¶
location = /otlp/v1/logs {
limit_except POST { deny all; }
limit_req zone=browser_logs burst=30 nodelay;
limit_req_status 429;
client_max_body_size 64k;
set $browser_logs_upstream http://otel-collector:4319/v1/logs;
proxy_pass $browser_logs_upstream;
}
The app sends its log records here as OTLP JSON, at most one batch a second, and nginx passes them to the collector's otlp/browser receiver (Loki has the rest of the path). Anyone can post to this path, so it takes POST only, bodies up to 64 KB, and 30 requests a minute per visitor address with a burst of 30, from the limit_req_zone at the top of the file; past that nginx answers 429. The upstream goes through a variable like the backend's, so nginx starts while the collector is down and this path returns 502 until it's back.
Static files and SPA routing¶
# Cache static assets; no add_header here, so the server-level security headers still apply
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
}
# HTML files should not be cached
location ~* \.html$ {
expires -1;
}
SvelteKit writes the JavaScript and CSS under _app/immutable/ with content hashes in their names, so a year of caching is safe. HTML gets expires -1 so the browser always fetches the current asset names. Every other path goes to location /, which serves 200.html when no file matches and lets the SvelteKit router handle the path. A missing file with one of the asset or .html extensions above gets a 404 instead, since its regex location has no fallback.
location = /grafana returns a 302 to ${GRAFANA_PUBLIC_URL}. There's no /grafana/ subpath proxy.
Grafana server¶
server {
listen 5001 ssl;
server_name grafana.integr8scode.cc;
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
resolver 127.0.0.11 valid=30s ipv6=off;
set $grafana_upstream ${GRAFANA_URL};
location / {
proxy_pass $grafana_upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto https;
}
location /api/live/ {
proxy_pass $grafana_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
Grafana gets its own hostname, grafana.integr8scode.cc, and is proxied at the root. grafana.ini sets no root_url; compose passes GF_SERVER_ROOT_URL from GRAFANA_ROOT_URL. /api/live/ is the Grafana Live websocket, so it gets the Upgrade and Connection headers.
The upstream goes through a variable with Docker's resolver (127.0.0.11), so nginx resolves grafana per request instead of at startup. Without that, nginx would refuse to start while Grafana is down. In that case the Grafana host just returns 502. This server block sets no security headers.
Environment variables¶
The nginx image runs envsubst on /etc/nginx/templates/*.template at startup and only replaces variables that are set, so nginx's own $host or $request_id stay intact.
# Production stage
FROM nginx:1.31-alpine AS production
# Upgrade the base image's packages to pick up fixes newer than the image, and add curl for the healthcheck and openssl for the certificate
RUN apk upgrade --no-cache && apk add --no-cache curl openssl
# Copy built static files
COPY --from=builder /app/build /usr/share/nginx/html
# Copy nginx config template (envsubst runs at container startup)
# The nginx image automatically processes /etc/nginx/templates/*.template
# and outputs to /etc/nginx/conf.d/ with the .template suffix removed
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
ENV GRAFANA_PUBLIC_URL=http://localhost:3000/
# Create writable directories for nginx (required for read-only root filesystem)
# and certs directory for TLS certificates
RUN mkdir -p /var/cache/nginx /var/run /etc/nginx/certs && \
chown -R nginx:nginx /var/cache/nginx /var/run /etc/nginx/certs
# nginx's entrypoint runs this before it starts; a certificate mounted at /etc/nginx/certs is kept as is
COPY --chmod=755 <<'EOF' /docker-entrypoint.d/05-self-signed-cert.sh
#!/bin/sh
set -e
if [ -s /etc/nginx/certs/server.crt ]; then
exit 0
fi
openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -quiet -subj "/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1" \
-keyout /etc/nginx/certs/server.key -out /etc/nginx/certs/server.crt
EOF
EXPOSE 5001
CMD ["nginx", "-g", "daemon off;"]
| Variable | Compose value | Used for |
|---|---|---|
BACKEND_URL |
https://backend:443 |
/api/ proxy |
GRAFANA_URL |
${GRAFANA_URL:-http://grafana:3000} |
Grafana server upstream |
GRAFANA_PUBLIC_URL |
${GRAFANA_ROOT_URL:-http://localhost:3000/} |
/grafana redirect target |
Applying changes¶
The template is baked into the image, so rebuild and recreate:
docker compose restart frontend keeps the old container and the old image, so it doesn't pick up a change. With pre-built images, docker compose pull frontend followed by docker compose up -d frontend does the same.
Troubleshooting¶
| Issue | Likely cause |
|---|---|
| SSE events arrive in batches or stop | SSE location missing proxy_buffering off or the 24h timeouts |
| CSP blocks a resource | Source missing from the csp directives in vite.config.ts; the browser console names the directive |
502 on /api/ |
Backend down: docker compose logs backend |
| 502 on the Grafana host | Observability profile not running |
| Security headers missing on a route | An add_header in that location; check with curl -kI |