Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:42:29 +08:00
commit 5d9c5c1010
21 changed files with 5694 additions and 0 deletions

View File

@@ -0,0 +1,296 @@
# Kubernetes ConfigMap Templates
---
# Template 1: Simple Key-Value Configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: <app-name>-config
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
app.kubernetes.io/instance: <instance-name>
data:
# Simple key-value pairs
APP_ENV: "production"
LOG_LEVEL: "info"
DATABASE_HOST: "db.example.com"
DATABASE_PORT: "5432"
CACHE_TTL: "3600"
MAX_CONNECTIONS: "100"
---
# Template 2: Configuration File
apiVersion: v1
kind: ConfigMap
metadata:
name: <app-name>-config-file
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
data:
# Application configuration file
application.yaml: |
server:
port: 8080
host: 0.0.0.0
logging:
level: INFO
format: json
database:
host: db.example.com
port: 5432
pool_size: 20
timeout: 30
cache:
enabled: true
ttl: 3600
max_entries: 10000
features:
new_ui: true
beta_features: false
---
# Template 3: Multiple Configuration Files
apiVersion: v1
kind: ConfigMap
metadata:
name: <app-name>-multi-config
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
data:
# Nginx configuration
nginx.conf: |
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
# Default site configuration
default.conf: |
server {
listen 80;
server_name _;
location / {
proxy_pass http://backend:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /health {
access_log off;
return 200 "healthy\n";
}
}
---
# Template 4: JSON Configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: <app-name>-json-config
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
data:
config.json: |
{
"server": {
"port": 8080,
"host": "0.0.0.0",
"timeout": 30
},
"database": {
"host": "postgres.example.com",
"port": 5432,
"database": "myapp",
"pool": {
"min": 2,
"max": 20
}
},
"redis": {
"host": "redis.example.com",
"port": 6379,
"db": 0
},
"features": {
"auth": true,
"metrics": true,
"tracing": true
}
}
---
# Template 5: Environment-Specific Configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: <app-name>-prod-config
namespace: production
labels:
app.kubernetes.io/name: <app-name>
environment: production
data:
APP_ENV: "production"
LOG_LEVEL: "warn"
DEBUG: "false"
RATE_LIMIT: "1000"
CACHE_TTL: "3600"
DATABASE_POOL_SIZE: "50"
FEATURE_FLAG_NEW_UI: "true"
FEATURE_FLAG_BETA: "false"
---
# Template 6: Script Configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: <app-name>-scripts
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
data:
# Initialization script
init.sh: |
#!/bin/bash
set -e
echo "Running initialization..."
# Wait for database
until nc -z $DATABASE_HOST $DATABASE_PORT; do
echo "Waiting for database..."
sleep 2
done
echo "Database is ready!"
# Run migrations
if [ "$RUN_MIGRATIONS" = "true" ]; then
echo "Running database migrations..."
./migrate up
fi
echo "Initialization complete!"
# Health check script
healthcheck.sh: |
#!/bin/bash
# Check application health endpoint
response=$(curl -sf http://localhost:8080/health)
if [ $? -eq 0 ]; then
echo "Health check passed"
exit 0
else
echo "Health check failed"
exit 1
fi
---
# Template 7: Prometheus Configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: prometheus-config
namespace: monitoring
labels:
app.kubernetes.io/name: prometheus
data:
prometheus.yml: |
global:
scrape_interval: 15s
evaluation_interval: 15s
external_labels:
cluster: 'production'
region: 'us-west-2'
alerting:
alertmanagers:
- static_configs:
- targets:
- alertmanager:9093
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
target_label: __address__
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
---
# Usage Examples:
#
# 1. Mount as environment variables:
# envFrom:
# - configMapRef:
# name: <app-name>-config
#
# 2. Mount as files:
# volumeMounts:
# - name: config
# mountPath: /etc/app
# volumes:
# - name: config
# configMap:
# name: <app-name>-config-file
#
# 3. Mount specific keys as files:
# volumes:
# - name: nginx-config
# configMap:
# name: <app-name>-multi-config
# items:
# - key: nginx.conf
# path: nginx.conf
#
# 4. Use individual environment variables:
# env:
# - name: LOG_LEVEL
# valueFrom:
# configMapKeyRef:
# name: <app-name>-config
# key: LOG_LEVEL

View File

@@ -0,0 +1,203 @@
# Production-Ready Kubernetes Deployment Template
# Replace all <placeholders> with actual values
apiVersion: apps/v1
kind: Deployment
metadata:
name: <app-name>
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
app.kubernetes.io/instance: <instance-name>
app.kubernetes.io/version: "<version>"
app.kubernetes.io/component: <component> # backend, frontend, database, cache
app.kubernetes.io/part-of: <system-name>
app.kubernetes.io/managed-by: kubectl
annotations:
description: "<application description>"
contact: "<team-email>"
spec:
replicas: 3 # Minimum 3 for production HA
revisionHistoryLimit: 10
selector:
matchLabels:
app.kubernetes.io/name: <app-name>
app.kubernetes.io/instance: <instance-name>
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0 # Zero-downtime deployment
minReadySeconds: 10
progressDeadlineSeconds: 600
template:
metadata:
labels:
app.kubernetes.io/name: <app-name>
app.kubernetes.io/instance: <instance-name>
app.kubernetes.io/version: "<version>"
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
prometheus.io/path: "/metrics"
spec:
serviceAccountName: <app-name>
# Pod-level security context
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
# Init containers (optional)
initContainers:
- name: init-wait
image: busybox:1.36
command: ['sh', '-c', 'echo "Initializing..."']
securityContext:
allowPrivilegeEscalation: false
runAsNonRoot: true
runAsUser: 1000
containers:
- name: <container-name>
image: <registry>/<image>:<tag> # Never use :latest
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 8080
protocol: TCP
- name: metrics
containerPort: 9090
protocol: TCP
# Environment variables
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
# Load from ConfigMap and Secret
envFrom:
- configMapRef:
name: <app-name>-config
- secretRef:
name: <app-name>-secret
# Resource limits
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
# Startup probe (for slow-starting apps)
startupProbe:
httpGet:
path: /health/startup
port: http
initialDelaySeconds: 0
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 30 # 5 minutes to start
# Liveness probe
livenessProbe:
httpGet:
path: /health/live
port: http
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
# Readiness probe
readinessProbe:
httpGet:
path: /health/ready
port: http
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
# Volume mounts
volumeMounts:
- name: tmp
mountPath: /tmp
- name: cache
mountPath: /app/cache
# - name: data
# mountPath: /var/lib/app
# Container security context
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 1000
capabilities:
drop:
- ALL
# Lifecycle hooks
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 15"] # Graceful shutdown
# Volumes
volumes:
- name: tmp
emptyDir: {}
- name: cache
emptyDir:
sizeLimit: 1Gi
# - name: data
# persistentVolumeClaim:
# claimName: <app-name>-data
# Scheduling
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app.kubernetes.io/name: <app-name>
topologyKey: kubernetes.io/hostname
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/name: <app-name>
terminationGracePeriodSeconds: 30
# Image pull secrets (if using private registry)
# imagePullSecrets:
# - name: regcred

View File

@@ -0,0 +1,171 @@
# Kubernetes Service Templates
---
# Template 1: ClusterIP Service (Internal Only)
apiVersion: v1
kind: Service
metadata:
name: <app-name>
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
app.kubernetes.io/instance: <instance-name>
annotations:
description: "Internal service for <app-name>"
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: <app-name>
app.kubernetes.io/instance: <instance-name>
ports:
- name: http
port: 80
targetPort: http # Named port from container
protocol: TCP
sessionAffinity: None
---
# Template 2: LoadBalancer Service (External Access)
apiVersion: v1
kind: Service
metadata:
name: <app-name>-lb
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
annotations:
# AWS NLB annotations
service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"
service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true"
# SSL certificate (optional)
# service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:..."
spec:
type: LoadBalancer
externalTrafficPolicy: Local # Preserves client IP
selector:
app.kubernetes.io/name: <app-name>
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
- name: https
port: 443
targetPort: https
protocol: TCP
# Restrict access to specific IPs (optional)
# loadBalancerSourceRanges:
# - 203.0.113.0/24
---
# Template 3: NodePort Service (Direct Node Access)
apiVersion: v1
kind: Service
metadata:
name: <app-name>-np
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
spec:
type: NodePort
selector:
app.kubernetes.io/name: <app-name>
ports:
- name: http
port: 80
targetPort: 8080
nodePort: 30080 # Optional, 30000-32767 range
protocol: TCP
---
# Template 4: Headless Service (StatefulSet)
apiVersion: v1
kind: Service
metadata:
name: <app-name>-headless
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
spec:
clusterIP: None # Headless
selector:
app.kubernetes.io/name: <app-name>
ports:
- name: client
port: 9042
targetPort: 9042
publishNotReadyAddresses: true # Include not-ready pods in DNS
---
# Template 5: Multi-Port Service with Metrics
apiVersion: v1
kind: Service
metadata:
name: <app-name>-multi
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
prometheus.io/path: "/metrics"
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: <app-name>
ports:
- name: http
port: 80
targetPort: 8080
protocol: TCP
- name: https
port: 443
targetPort: 8443
protocol: TCP
- name: grpc
port: 9090
targetPort: 9090
protocol: TCP
- name: metrics
port: 9091
targetPort: 9091
protocol: TCP
---
# Template 6: Service with Session Affinity
apiVersion: v1
kind: Service
metadata:
name: <app-name>-sticky
namespace: <namespace>
labels:
app.kubernetes.io/name: <app-name>
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: <app-name>
ports:
- name: http
port: 80
targetPort: 8080
protocol: TCP
sessionAffinity: ClientIP
sessionAffinityConfig:
clientIP:
timeoutSeconds: 10800 # 3 hours
---
# Template 7: ExternalName Service (External Service Mapping)
apiVersion: v1
kind: Service
metadata:
name: external-db
namespace: <namespace>
spec:
type: ExternalName
externalName: db.example.com
ports:
- port: 5432
targetPort: 5432
protocol: TCP