Introduction
This tutorial shows how to deploy two app servers behind a Hetzner Cloud Load Balancer with TLS (Transport Layer Security) termination using a Cloudflare Origin Certificate. The entire infrastructure is managed with Pulumi and TypeScript.
If you have already followed the TLS Termination on Hetzner Load Balancer using Pulumi tutorial, this tutorial covers the same architecture but replaces the Hetzner managed certificate with a Cloudflare Origin Certificate. The key differences are:
| Hetzner Managed Certificate | Cloudflare Origin Certificate | |
|---|---|---|
| DNS requirement | Hetzner DNS | Cloudflare DNS |
| Certificate validity | 90 days (auto-renewed) | Up to 15 years |
| Real server IP exposed | Yes | No — Cloudflare proxies traffic |
| DDoS protection | No | Yes (free) |
| Bot detection | No | Yes (free) |
By the end of this tutorial you will have:
- A private network with two Ubuntu app servers
- A Hetzner Load Balancer that terminates TLS using a Cloudflare Origin Certificate
- HTTPS on port 443 with HTTP-to-HTTPS redirect on port 80
- A Cloudflare proxied DNS A record created automatically by Pulumi
- App servers that receive plain HTTP on port 80 — no TLS configuration needed on the servers
Prerequisites
- A domain added to Cloudflare (a free Cloudflare account is sufficient)
- Hetzner Cloud account with an API token (Project → Security → API Tokens → Read & Write)
- Node.js 18 or later
- Pulumi CLI installed and logged in:
pulumi login --local
Example terminology
| Placeholder | Example value |
|---|---|
<domain> |
example.com |
<your-zone-id> |
abc123def456 |
<your-hetzner-token> |
AbCdEfGhIj... |
<your-cloudflare-token> |
XyZaBcDeF... |
Architecture
Internet → Cloudflare Edge (DDoS protection, bot detection)
↓ HTTPS (443)
Hetzner Load Balancer (TLS terminated)
↓ HTTP (80) via private network
app-1 (10.44.10.11) app-2 (10.44.10.12)Traffic flows through Cloudflare's edge before reaching the Load Balancer. Cloudflare terminates the public-facing TLS connection and forwards requests to the Load Balancer over HTTPS using the Origin Certificate. The Load Balancer then forwards plain HTTP to the app servers over the private network.
The Cloudflare Origin Certificate is only trusted by Cloudflare's edge — not by browsers directly. Your domain must use Cloudflare as a DNS proxy (the orange cloud must be enabled) for HTTPS to work correctly. Direct access to the Load Balancer IP will show a certificate warning.
Step 1 - Generate a Cloudflare Origin Certificate
A Cloudflare Origin Certificate is a TLS certificate issued by Cloudflare for communication between Cloudflare's edge and your origin server (the Load Balancer in this case). It is valid for up to 15 years and requires no renewal process.
Step 1.1 - Create the certificate
- Go to dash.cloudflare.com and select your domain
- Navigate to SSL/TLS → Origin Server
- Click Create Certificate
- Keep the defaults: Let Cloudflare generate a private key and a CSR, key type RSA (2048), validity 15 years
- Confirm that your domain hostname is listed under Hostnames
- Click Create
Step 1.2 - Save the certificate and private key
Cloudflare shows the certificate and private key only once. You will paste both into your .env file in Step 2 — keep this browser tab open until then.
Cloudflare does not store the private key and cannot show it again. Do not close the dialog before copying it.
Step 1.3 - Get your Cloudflare Zone ID
- On the Cloudflare dashboard, select your domain
- On the Overview page, scroll down to the API section on the right
- Copy the Zone ID — you will need it in Step 3
Step 1.4 - Create a Cloudflare API token
The Pulumi program needs a Cloudflare API token to create the DNS A record.
- Go to dash.cloudflare.com → My Profile → API Tokens
- Click Create Token → Create Custom Token
- Set the permission: Zone → DNS → Edit
- Under Zone Resources, select Specific zone → your domain
- Click Continue to summary → Create Token
- Copy the token — it is shown only once
Step 2 - Set up the Pulumi project
Create the project directory and initialize a new Pulumi TypeScript project:
mkdir hetzner-cloudflare-lb-pulumi && cd hetzner-cloudflare-lb-pulumi
pulumi new typescript -y
npm install @pulumi/hcloud @pulumi/cloudflareCreate a .env file with your credentials and configuration. All sensitive values live here — the Pulumi program and providers read them directly from the environment:
HCLOUD_TOKEN=<your-hetzner-token>
CLOUDFLARE_API_TOKEN=<your-cloudflare-token>
CLOUDFLARE_ZONE_ID=<your-zone-id>
DOMAIN=<domain>
TLS_CERT="-----BEGIN CERTIFICATE-----
...paste your certificate content here...
-----END CERTIFICATE-----"
TLS_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----
...paste your private key content here...
-----END PRIVATE KEY-----"
PULUMI_CONFIG_PASSPHRASE=<choose-a-strong-passphrase>The certificate and private key are multiline PEM values. Wrap them in double quotes as shown above so they are read correctly when you run source .env.
Add .env to .gitignore so your credentials are never committed:
echo ".env" >> .gitignoreLoad the environment variables, then configure the two machine-specific values that are not credentials:
Replace
~/.ssh/id_rsa.pubwith the path to your public key if it is different.
set -a && source .env && set +a
pulumi config set sshPublicKeyPath ~/.ssh/id_rsa.pub
pulumi config set sshAllowedCidrs "[\"$(curl -4 https://ip.hetzner.com)/32\"]"| Description | |
|---|---|
HCLOUD_TOKEN, CLOUDFLARE_API_TOKEN |
These are picked up automatically by the Hetzner and Cloudflare providers from the environment — no pulumi config set needed for them. |
DOMAIN, CLOUDFLARE_ZONE_ID, TLS_CERT, TLS_PRIVATE_KEY |
These are read directly by the Pulumi program via process.env. The certificate and private key are wrapped in pulumi.secret() in the code so they are encrypted in the Pulumi state file and never logged in plain text. |
Step 3 - Write the Pulumi program
Replace the contents of index.ts with the full program below. Then create the cloud-init file for the app servers.
index.ts
import * as fs from "node:fs";
import * as path from "node:path";
import * as pulumi from "@pulumi/pulumi";
import * as hcloud from "@pulumi/hcloud";
import * as cloudflare from "@pulumi/cloudflare";
const stack = pulumi.getStack();
const project = pulumi.getProject();
const config = new pulumi.Config();
const projectConfig = new pulumi.Config(project);
// Read from environment variables (loaded from .env via set -a && source .env && set +a)
const domain = process.env.DOMAIN;
const cloudflareZoneId = process.env.CLOUDFLARE_ZONE_ID;
const tlsCertificate = process.env.TLS_CERT;
const tlsPrivateKey = process.env.TLS_PRIVATE_KEY;
if (!domain) throw new pulumi.RunError("DOMAIN must be set in .env");
if (!cloudflareZoneId) throw new pulumi.RunError("CLOUDFLARE_ZONE_ID must be set in .env");
if (!tlsCertificate) throw new pulumi.RunError("TLS_CERT must be set in .env");
if (!tlsPrivateKey) throw new pulumi.RunError("TLS_PRIVATE_KEY must be set in .env");
const existingSshKeyName = config.get("sshKeyName");
const sshPublicKeyPath = config.get("sshPublicKeyPath");
const sshAllowedCidrs = config.getObject<string[]>("sshAllowedCidrs") ?? [];
if (!existingSshKeyName && !sshPublicKeyPath) {
throw new pulumi.RunError(
"Set either `sshKeyName` (existing Hetzner SSH key name) or `sshPublicKeyPath` (local public key path).",
);
}
const location = projectConfig.get("location") ?? "nbg1";
const networkZone = projectConfig.get("networkZone") ?? "eu-central";
const loadBalancerType = projectConfig.get("loadBalancerType") ?? "lb11";
const serverType = projectConfig.get("serverType") ?? "cx23";
const image = projectConfig.get("image") ?? "ubuntu-24.04";
const networkCidr = projectConfig.get("networkCidr") ?? "10.44.0.0/16";
const privateSubnetCidr = projectConfig.get("privateSubnetCidr") ?? "10.44.10.0/24";
const loadBalancerPrivateIpAddress = projectConfig.get("loadBalancerPrivateIp") ?? "10.44.10.10";
const appPrivateIp1 = projectConfig.get("appPrivateIp1") ?? "10.44.10.11";
const appPrivateIp2 = projectConfig.get("appPrivateIp2") ?? "10.44.10.12";
const namePrefix = `${project}-${stack}`;
const sshPublicKey = sshPublicKeyPath
? fs
.readFileSync(path.resolve(sshPublicKeyPath.replace(/^~(?=$|\/|\\)/, process.env.HOME ?? "~")), "utf-8")
.trim()
: undefined;
const labels = {
project,
stack,
managedBy: "pulumi",
role: "tutorial",
};
// --- Providers ---
// Providers read HCLOUD_TOKEN and CLOUDFLARE_API_TOKEN from the environment automatically.
const hcloudProvider = new hcloud.Provider("hcloud", {});
const hcloudOpts: pulumi.CustomResourceOptions = { provider: hcloudProvider };
const cloudflareProvider = new cloudflare.Provider("cloudflare", {});
const cloudflareOpts: pulumi.CustomResourceOptions = { provider: cloudflareProvider };
// --- Network ---
const network = new hcloud.Network("private-network", {
name: `${namePrefix}-network`,
ipRange: networkCidr,
labels,
}, hcloudOpts);
const networkId = network.id.apply((id) => Number(id));
const privateSubnet = new hcloud.NetworkSubnet("private-subnet", {
networkId,
type: "cloud",
networkZone,
ipRange: privateSubnetCidr,
}, hcloudOpts);
// --- SSH key ---
const sshKeyRef: pulumi.Input<string> = existingSshKeyName
? existingSshKeyName
: new hcloud.SshKey("deployer-key", {
name: `${namePrefix}-ssh-key`,
publicKey: sshPublicKey!,
labels,
}, hcloudOpts).id;
// --- Firewall ---
// App servers accept HTTP only from the LB private IP.
// SSH is restricted to your allowed CIDRs.
// Port 443 is not needed on the servers — TLS is terminated at the Load Balancer.
const appFirewall = new hcloud.Firewall("app-firewall", {
name: `${namePrefix}-app-fw`,
labels: { ...labels, tier: "app" },
rules: [
{
description: "HTTP from load balancer private IP only",
direction: "in",
protocol: "tcp",
port: "80",
sourceIps: [`${loadBalancerPrivateIpAddress}/32`],
},
...sshAllowedCidrs.map((cidr, index) => ({
description: `SSH allowlist entry ${index + 1}`,
direction: "in" as const,
protocol: "tcp" as const,
port: "22",
sourceIps: [cidr],
})),
],
}, hcloudOpts);
const appFirewallId = appFirewall.id.apply((id) => Number(id));
// --- App servers ---
const cloudInitTemplate = fs.readFileSync(
path.join(__dirname, "cloud-init", "app-server.yaml"),
"utf-8"
);
const serverDefs = [
{ suffix: "app-1", privateIp: appPrivateIp1 },
{ suffix: "app-2", privateIp: appPrivateIp2 },
];
const appServers = serverDefs.map((def) => {
const userData = cloudInitTemplate
.split("${SERVER_NAME}").join(`${namePrefix}-${def.suffix}`)
.split("${SERVER_PRIVATE_IP}").join(def.privateIp);
return new hcloud.Server(`server-${def.suffix}`, {
name: `${namePrefix}-${def.suffix}`,
serverType,
image,
location,
sshKeys: [sshKeyRef],
firewallIds: [appFirewallId],
publicNets: [{ ipv4Enabled: true, ipv6Enabled: false }],
networks: [{ networkId, ip: def.privateIp }],
userData,
labels: { ...labels, tier: "app", instance: def.suffix },
}, { ...hcloudOpts, dependsOn: [privateSubnet] });
});
// --- Load Balancer ---
const loadBalancer = new hcloud.LoadBalancer("public-load-balancer", {
name: `${namePrefix}-lb`,
loadBalancerType,
location,
labels: { ...labels, tier: "edge" },
}, hcloudOpts);
const loadBalancerIdNumber = loadBalancer.id.apply((id) => Number(id));
const loadBalancerNetwork = new hcloud.LoadBalancerNetwork("private-network-attachment", {
loadBalancerId: loadBalancerIdNumber,
subnetId: privateSubnet.id,
ip: loadBalancerPrivateIpAddress,
enablePublicInterface: true,
}, { ...hcloudOpts, dependsOn: [privateSubnet, loadBalancer] });
const loadBalancerTargets = appServers.map((server, i) => {
const serverId = server.id.apply((id) => Number(id));
return new hcloud.LoadBalancerTarget(`app-target-${i + 1}`, {
type: "server",
loadBalancerId: loadBalancerIdNumber,
serverId,
usePrivateIp: true,
}, { ...hcloudOpts, dependsOn: [loadBalancerNetwork, server] });
});
// --- Cloudflare Origin Certificate uploaded to Hetzner ---
// The certificate is generated in the Cloudflare dashboard and valid for 15 years.
// It is trusted only by Cloudflare's edge — traffic must be proxied through Cloudflare.
const certificate = new hcloud.UploadedCertificate("tls-cert", {
name: `${namePrefix}-cert`,
certificate: pulumi.secret(tlsCertificate),
privateKey: pulumi.secret(tlsPrivateKey),
labels,
}, { ...hcloudOpts, dependsOn: loadBalancerTargets });
// --- LB services ---
// HTTPS on port 443 terminates TLS and forwards to servers on port 80.
// HTTP on port 80 redirects all traffic to HTTPS.
const httpsService = new hcloud.LoadBalancerService("https-service", {
loadBalancerId: loadBalancer.id,
protocol: "https",
listenPort: 443,
destinationPort: 80,
http: {
certificates: [certificate.id.apply((id) => Number(id))],
redirectHttp: true,
},
healthCheck: {
protocol: "http",
port: 80,
interval: 10,
timeout: 5,
retries: 3,
http: {
path: "/health",
statusCodes: ["200"],
response: "ok",
},
},
}, { ...hcloudOpts, dependsOn: [certificate] });
// --- Cloudflare DNS A record ---
// Proxied: traffic routes through Cloudflare before reaching the Load Balancer.
// This hides the real Load Balancer IP and enables DDoS protection and bot detection.
const dnsRecord = new cloudflare.DnsRecord("lb-dns-record", {
zoneId: cloudflareZoneId,
name: "@",
type: "A",
content: loadBalancer.ipv4,
proxied: true,
ttl: 1,
}, { ...cloudflareOpts, dependsOn: [httpsService] });
// --- Outputs ---
export const loadBalancerPublicIpv4 = loadBalancer.ipv4;
export const appUrl = pulumi.interpolate`https://${domain}/`;
export const appHealthUrl = pulumi.interpolate`https://${domain}/health`;
export const server1Name = appServers[0].name;
export const server1PrivateIp = pulumi.output(appPrivateIp1);
export const server2Name = appServers[1].name;
export const server2PrivateIp = pulumi.output(appPrivateIp2);
export const cloudflareNote = pulumi.interpolate`Traffic is proxied through Cloudflare — the Load Balancer IP is hidden from the public`;Now create the cloud-init directory and file:
mkdir cloud-initcloud-init/app-server.yaml
#cloud-config
packages:
- nginx
write_files:
- path: /var/www/html/index.html
permissions: "0644"
owner: root:root
content: |
<html>
<head>
<title>${SERVER_NAME}</title>
<style>
body {
font-family: system-ui, sans-serif;
max-width: 760px;
margin: 40px auto;
padding: 0 16px;
line-height: 1.5;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>Hello from ${SERVER_NAME}</h1>
<p>Traffic reached this server through the Hetzner Load Balancer over the private network.</p>
<p>Server: <code>${SERVER_NAME}</code></p>
<p>Private IP: <code>${SERVER_PRIVATE_IP}</code></p>
</body>
</html>
- path: /var/www/html/health
permissions: "0644"
owner: root:root
content: "ok"
- path: /etc/nginx/conf.d/app.conf
permissions: "0644"
owner: root:root
content: |
server {
listen 80;
server_name _;
include /etc/nginx/cloudflare-real-ip.conf;
real_ip_header CF-Connecting-IP;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
location /health {
try_files $uri =404;
}
}
- path: /usr/local/bin/update-cloudflare-ips
permissions: "0755"
owner: root:root
content: |
#!/bin/bash
# Fetches the latest Cloudflare IP ranges and updates the nginx real_ip config.
# Run on boot and weekly via cron to stay up to date.
set -euo pipefail
CONFIG_PATH=/etc/nginx/cloudflare-real-ip.conf
LB_IP=${SERVER_PRIVATE_IP}
: > "$CONFIG_PATH"
for type in v4 v6; do
curl -s "https://www.cloudflare.com/ips-$type" | \
sed 's/^/set_real_ip_from /; s/$/;/' | \
tee -a "$CONFIG_PATH" > /dev/null
done
echo "set_real_ip_from $LB_IP;" | tee -a "$CONFIG_PATH" > /dev/null
nginx -t && systemctl reload nginx
- path: /etc/cron.weekly/update-cloudflare-ips
permissions: "0755"
owner: root:root
content: |
#!/bin/bash
/usr/local/bin/update-cloudflare-ips
runcmd:
- /usr/local/bin/update-cloudflare-ips
- rm -f /etc/nginx/sites-enabled/default
- systemctl enable nginx
- systemctl restart nginxThe cloud-init installs nginx and sets up a script (
/usr/local/bin/update-cloudflare-ips) that fetches Cloudflare's current IP ranges fromhttps://www.cloudflare.com/ips-v4andhttps://www.cloudflare.com/ips-v6and writes them into/etc/nginx/cloudflare-real-ip.conf. This file is included by nginx to restore the real visitor IP from theCF-Connecting-IPheader — so$remote_addrin logs and applications always shows the real visitor IP, not Cloudflare's proxy IP. The script runs once on first boot and then weekly via cron to stay up to date as Cloudflare updates their ranges. In your own application, keep this script and theincludeandreal_ip_headerdirectives in your nginx config. The/healthendpoint must continue to returnokwith a200status for the Load Balancer health check to pass.
Step 4 - Deploy the infrastructure
Preview the changes before applying. Pulumi will create 15 resources:
set -a && source .env && set +a
pulumi previewThe preview lists: 1 SSH key, 1 network, 1 subnet, 1 firewall, 2 servers, 1 load balancer, 1 LB network attachment, 2 LB targets, 1 uploaded certificate, 1 LB service, and 1 Cloudflare DNS record.
If the preview looks correct, deploy:
pulumi upPulumi creates the Hetzner resources first, uploads the certificate, configures the HTTPS service, and then creates the Cloudflare DNS A record pointing to the Load Balancer IP. The DNS record is proxied, so the Load Balancer's real IP is never exposed publicly.
Step 5 - Verify
Once pulumi up completes, run the following checks:
curl https://<domain>/
curl https://<domain>/health # expected: ok
curl -I http://<domain>/ # expected: 301 redirect to HTTPSYou can also check the Cloudflare dashboard to confirm:
- The A record was created under DNS → Records
- The orange cloud icon (proxy) is enabled on the record
- The SSL/TLS mode is set to Full or Full (strict) under SSL/TLS → Overview
Set the SSL/TLS mode to Full (not Flexible). Flexible mode sends unencrypted traffic from Cloudflare to your origin, which defeats the purpose of the Origin Certificate. Full mode uses the Origin Certificate for the connection between Cloudflare and the Load Balancer.
Step 6 - Clean up
The Cloudflare DNS record is managed by Pulumi and will be deleted automatically. No manual cleanup is needed before destroying.
set -a && source .env && set +a
pulumi destroy
pulumi stack rm devConclusion
You deployed two app servers behind a Hetzner Load Balancer with TLS termination using a Cloudflare Origin Certificate — all managed with Pulumi and TypeScript. Traffic flows through Cloudflare's edge, which provides DDoS protection and bot detection for free, while the Load Balancer handles TLS termination so the app servers only receive plain HTTP on the private network.
Because traffic is proxied through Cloudflare, your app servers will see Cloudflare's edge IP addresses instead of the real visitor IPs. The real visitor IP is available in the
CF-Connecting-IPrequest header that Cloudflare adds to every request. Make sure your application reads from that header when logging or rate-limiting by IP.
Next steps:
- Replace the demo nginx config in
cloud-init/app-server.yamlwith your own application — keep theset_real_ip_fromandreal_ip_headerdirectives so real visitor IPs are preserved - Add more servers by extending the
serverDefsarray inindex.ts - Enable Cloudflare Full (strict) SSL/TLS mode for stricter certificate validation
- Explore Cloudflare's free WAF (Web Application Firewall) rules under Security → WAF
Full source code: infra-labs