Certainly! I'll provide a step-by-step guide to help you deploy your backend project on Hetzner Cloud infrastructure using the tools and technologies you've specified. We'll prioritize tools that are user-friendly and have a user interface (UI) where possible. If any tools overlap in functionality, we'll choose the most suitable one and omit the redundant ones.
Overview
Technologies and Tools:
- Programming Languages and Frameworks: TypeScript, Node.js (>20), pnpm, Babel
- Source Control and CI/CD: GitHub, GitHub Actions
- Containerization and Orchestration: Docker, containerd, Kubernetes, Helm, Docker Hub
- Infrastructure and Deployment Tools: Hetzner Cloud, Terraform, Cluster API Provider Hetzner
- Kubernetes Tools: MicroK8s, Calico, KEDA, Traefik, Cert-Manager, Helm
- Database: MongoDB Atlas
- Other Tools: KEDA for autoscaling
Primary Goals:
- Host the backend project on Hetzner Cloud using dedicated machines.
- Implement load balancing and horizontal scaling.
- Ensure high availability and fault tolerance.
- Set up CI/CD pipelines with GitHub Actions.
- Use containerd as the Kubernetes container runtime.
- Implement multi-stage Docker builds to reduce image size.
- Enable Horizontal Pod Autoscaling (HPA).
- Add readiness and liveness probes.
- Leverage caching in GitHub Actions.
- Scale the cluster nodes based on demand using Hetzner Cluster API.
- Expose the application securely over the internet with a static route.
- Ensure the health endpoint (
/_health) is monitored every 10 seconds.
Step-by-Step Guide
Prerequisites
- Hetzner Cloud Account: Sign up for a Hetzner Cloud account if you haven't already.
- API Tokens: Obtain API tokens for Hetzner Cloud and Docker Hub.
- SSH Key Pair: Generate an SSH key pair for accessing your servers.
- Domain Name: Purchase a domain or subdomain to expose your application.
- Local Machine Setup: Install the following tools on your local machine:
kubectl (Kubernetes command-line tool)
helm (Helm package manager)
terraform (Infrastructure as Code tool)
docker (For building images locally)
pnpm (Package manager)
git (Version control)
1. Set Up Infrastructure with Terraform and Cluster API Provider Hetzner
1.1. Install Terraform
Install Terraform on your local machine following the instructions for your OS from the official Terraform website.
1.2. Configure Terraform for Hetzner
Create a new directory for your infrastructure code:
mkdir hetzner-k8s-cluster
cd hetzner-k8s-cluster
1.3. Initialize Terraform Configuration
Create a main.tf file with the following content:
# main.tf
terraform {
required_version = ">= 1.0.0"
required_providers {
hcloud = {
source = "hetznercloud/hcloud"
version = "~> 1.32.2"
}
}
}
provider "hcloud" {
token = var.hcloud_token
}
variable "hcloud_token" {}
resource "hcloud_server" "k8s_master" {
name = "k8s-master"
server_type = "cx31"
image = "ubuntu-22.04"
location = "nbg1"
ssh_keys = [var.ssh_key_name]
}
# Define resource for worker nodes (e.g., autoscaling group) here if necessary
1.4. Create Variables File
Create a variables.tf file:
# variables.tf
variable "hcloud_token" {
description = "Hetzner Cloud API token"
}
variable "ssh_key_name" {
description = "Name of the SSH key uploaded to Hetzner"
}
1.5. Add SSH Key to Hetzner
Upload your public SSH key to Hetzner Cloud:
- Navigate to Hetzner Cloud Console.
- Go to "SSH Keys" and add your SSH public key.
- Note the name you give to your key; it will be used in
terraform.tfvars.
1.6. Create Terraform Variables File
Create a terraform.tfvars file:
# terraform.tfvars
hcloud_token = "your_hetzner_api_token"
ssh_key_name = "your_ssh_key_name_in_hetzner"
1.7. Initialize and Apply Terraform Configuration
terraform init
terraform apply
This will provision a master server on Hetzner Cloud.
2. Bootstrap Kubernetes Cluster with MicroK8s
Since we have a single master node, we'll use MicroK8s for a lightweight Kubernetes deployment.
2.1. Install MicroK8s on the Master Node
SSH into the master node:
ssh root@k8s-master-ip-address
Install MicroK8s:
snap install microk8s --classic --channel=1.28/stable
Add your user to the MicroK8s group:
useradd -m -G microk8s ubuntu
chown -f -R ubuntu ~/.kube
2.2. Enable Necessary MicroK8s Add-ons
microk8s enable dns storage ingress metallb:192.168.1.240-192.168.1.250
2.3. Configure MicroK8s to Use Containerd
MicroK8s uses containerd by default. Verify:
microk8s inspect
3. Set Up Networking with Calico
MicroK8s can enable Calico as a network add-on.
3.1. Enable Calico in MicroK8s
microk8s enable calico
4. Install Helm for Kubernetes Package Management
4.1. Install Helm on Your Local Machine
Follow the instructions from the official Helm website to install Helm.
4.2. Set Up Kubeconfig for Remote Access
On your local machine, fetch the kubeconfig from the master node:
ssh root@k8s-master-ip-address "microk8s config" > kubeconfig
export KUBECONFIG=./kubeconfig
5. Install Traefik Ingress Controller
Traefik will handle ingress and load balancing for your services.
5.1. Add Traefik Helm Repository
helm repo add traefik https://helm.traefik.io/traefik
helm repo update
5.2. Install Traefik with Helm
helm install traefik traefik/traefik --namespace traefik --create-namespace
6. Set Up Cert-Manager for Automatic TLS Certificates
Cert-Manager will provision Let's Encrypt certificates for your domains.
6.1. Add Cert-Manager Helm Repository
helm repo add jetstack https://charts.jetstack.io
helm repo update
6.2. Install Cert-Manager
helm install cert-manager jetstack/cert-manager \
--namespace cert-manager --create-namespace \
--set installCRDs=true
6.3. Create Let's Encrypt ClusterIssuer
Create a file named cluster-issuer.yaml:
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt
spec:
acme:
email: your-email@example.com
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-account-key
solvers:
- http01:
ingress:
class: traefik
Apply the issuer:
kubectl apply -f cluster-issuer.yaml
7. Prepare Your Application for Deployment
7.1. Implement Multi-Stage Docker Builds
Create a Dockerfile in your project root:
# Stage 1: Builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm
RUN pnpm install
COPY . .
RUN pnpm run build
# Stage 2: Production
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"]
This approach reduces the final image size by only including the necessary production files.
7.2. Create Helm Chart for Your Application
Generate a new Helm chart:
helm create my-backend-app
Customize the generated chart:
-
Deployment Template (deployment.yaml):
-
Update the image repository to your Docker Hub repository.
-
Add readiness and liveness probes using the /_health endpoint.
-
Example:
readinessProbe:
httpGet:
path: /_health
port: http
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /_health
port: http
initialDelaySeconds: 15
periodSeconds: 20
-
Service Template (service.yaml):
- Set the service type to
ClusterIP.
-
Ingress Template (ingress.yaml):
-
Configure ingress rules with Traefik annotations for TLS.
-
Example:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-backend-app
annotations:
kubernetes.io/ingress.class: traefik
cert-manager.io/cluster-issuer: letsencrypt
spec:
tls:
- hosts:
- api.example.com
secretName: my-backend-app-tls
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-backend-app
port:
number: 3000
-
Values File (values.yaml):
- Set the
image.repository to your Docker Hub repository.
- Configure resources and autoscaling settings.
7.3. Push Your Docker Image to Docker Hub
You'll set up GitHub Actions to build and push your Docker image automatically.
8. Setup CI/CD Pipeline with GitHub Actions
8.1. Create GitHub Actions Workflow
Create .github/workflows/main.yml in your repository:
name: CI/CD Pipeline
on:
push:
branches: [ main ]
env:
REGISTRY: docker.io
IMAGE_NAME: your-dockerhub-username/your-app
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
cache: 'pnpm'
- name: Install Dependencies
run: |
npm install -g pnpm
pnpm install
- name: Build Application
run: pnpm run build
- name: Build and Push Docker Image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: ${{ env.IMAGE_NAME }}:${{ github.sha }}
secrets: |
DOCKERHUB_USERNAME=${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN=${{ secrets.DOCKERHUB_TOKEN }}
cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:cache
cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:cache,mode=max
- name: Deploy to Kubernetes
uses: appleboy/ssh-action@v0.1.8
with:
host: ${{ secrets.K8S_MASTER_IP }}
username: ${{ secrets.K8S_USER }}
key: ${{ secrets.K8S_SSH_KEY }}
script: |
export KUBECONFIG=/home/ubuntu/.kube/config
helm upgrade --install my-backend-app ./my-backend-app \
--set image.repository=${{ env.IMAGE_NAME }} \
--set image.tag=${{ github.sha }} \
--namespace default
8.2. Add Secrets to GitHub Repository
Go to your GitHub repository settings and add the following secrets:
DOCKERHUB_USERNAME
DOCKERHUB_TOKEN
K8S_MASTER_IP (Public IP of your Kubernetes master node)
K8S_USER (SSH user, e.g., ubuntu)
K8S_SSH_KEY (Private SSH key for the user)
8.3. Leverage Caching in GitHub Actions
The setup-node action with cache: 'pnpm' enables dependency caching. Also, docker/build-push-action uses build cache.
9. Implement Horizontal Pod Autoscaling with KEDA
KEDA allows Kubernetes to scale pods based on external metrics like CPU usage.
9.1. Add KEDA Helm Repository and Install
helm repo add kedacore https://kedacore.github.io/charts
helm repo update
helm install keda kedacore/keda --namespace keda --create-namespace
9.2. Configure Autoscaling for Your Application
Create a scaledobject.yaml in your Helm chart's templates directory:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: my-backend-app-scaledobject
namespace: default
spec:
scaleTargetRef:
name: my-backend-app
triggers:
- type: cpu
metadata:
type: Utilization
value: "50"
This will scale your deployment based on CPU utilization.
10. Configure Node Autoscaling with Cluster API
To scale nodes based on demand, we'll configure the Cluster API Provider Hetzner.
10.1. Install Cluster API CLI
Install clusterctl:
curl -L https://github.com/kubernetes-sigs/cluster-api/releases/download/v1.4.2/clusterctl-linux-amd64 -o clusterctl
chmod +x clusterctl
sudo mv clusterctl /usr/local/bin/
10.2. Initialize Cluster API
clusterctl init --infrastructure hetzner
10.3. Configure MachineDeployment for Worker Nodes
Create a machinedeployment.yaml:
apiVersion: cluster.x-k8s.io/v1beta1
kind: MachineDeployment
metadata:
name: worker-node-md-0
namespace: default
spec:
clusterName: my-cluster
replicas: 2
selector:
matchLabels:
cluster.x-k8s.io/cluster-name: my-cluster
template:
metadata:
labels:
cluster.x-k8s.io/cluster-name: my-cluster
spec:
bootstrap:
configRef:
apiVersion: bootstrap.cluster.x-k8s.io/v1beta1
kind: KubeadmConfigTemplate
name: worker-node-config
infrastructureRef:
apiVersion: infrastructure.cluster.x-k8s.io/v1beta1
kind: HetznerMachineTemplate
name: worker-node-template
Apply the configuration:
kubectl apply -f machinedeployment.yaml
10.4. Configure Cluster Autoscaler
Install the Cluster Autoscaler:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/autoscaler/release-1.28/cluster-autoscaler-autodiscover.yaml
Edit the deployment to specify the cloud provider and parameters:
kubectl edit deployment cluster-autoscaler -n kube-system
Set the following command arguments:
spec:
template:
spec:
containers:
- command:
- ./cluster-autoscaler
- --v=4
- --cloud-provider=hetzner
- --skip-nodes-with-local-storage=false
- --nodes=2:10:worker-node-md-0
11. Add Readiness and Liveness Probes
Already covered in Step 7.2.
12. Expose the Application Securely Over the Internet
Your application is already exposed via Traefik with TLS certificates provided by Cert-Manager.
Ensure your DNS records point to the public IP address of your ingress controller (Traefik).
13. Monitor the Health Endpoint
The Kubernetes probes will check the /_health endpoint every 10 seconds. If the endpoint fails, Kubernetes will restart the pod.
Additionally, you can set up monitoring tools like Prometheus and Grafana for more in-depth monitoring.
14. Optional: Secure Service Mesh with Kuma
Since Traefik and Cert-Manager handle ingress and TLS, you might not need Kuma unless you require advanced features like traffic policies or mutual TLS between services.
If you decide to use Kuma:
14.1. Install Kuma
helm repo add kuma https://kumahq.github.io/charts
helm repo update
helm install kuma kuma/kuma --namespace kuma-system --create-namespace
14.2. Enable mTLS
Apply a Mesh policy:
apiVersion: kuma.io/v1alpha1
kind: Mesh
metadata:
name: default
spec:
mtls:
enabledBackend: ca-1
backends:
- name: ca-1
type: builtin
Final Notes
- Tools Simplification: We omitted Trust Manager because Cert-Manager handles certificate management.
- User Interfaces: Helm and Traefik provide user-friendly interfaces.
- Security: Always secure your secrets and credentials.
- Testing: Test each part of the setup in a development environment before deploying to production.
- Documentation: Keep your configurations and steps documented for future reference.
By following these steps, you'll have a robust, scalable, and secure backend application running on Hetzner Cloud with automatic scaling and monitoring in place.
If you have any questions or need further assistance with any of the steps, feel free to ask!