Cloud-Native Development: Bulut Odaklı Uygulama Geliştirme

Cloud-native development, uygulamaları bulut ortamının avantajlarından tam olarak yararlanacak şekilde tasarlama ve geliştirme yaklaşımıdır.

Cloud-Native Nedir?

Cloud-native, uygulamaların bulut ortamında doğal olarak çalışacak şekilde tasarlandığı bir yaklaşımdır. Bu yaklaşım, ölçeklenebilirlik, esneklik ve dayanıklılık gibi bulut avantajlarından maksimum fayda sağlar.

Temel Prensipler

  • Microservices: Uygulamaları küçük, bağımsız servislere bölme
  • Containerization: Docker container'ları ile paketleme
  • Orchestration: Kubernetes ile container yönetimi
  • DevOps: Geliştirme ve operasyon süreçlerinin entegrasyonu

Cloud-Native Mimarisi

12-Factor App Methodology

# 1. Codebase - Tek kod deposu
git clone https://github.com/company/app.git

# 2. Dependencies - Bağımlılıkları açıkça belirt
# requirements.txt
Flask==2.0.1
redis==3.5.3

# 3. Config - Konfigürasyonu ortam değişkenlerinde sakla
export DATABASE_URL=postgresql://user:pass@localhost/db
export REDIS_URL=redis://localhost:6379

# 4. Backing Services - Dış servisleri kaynak olarak kullan
# Herhangi bir veritabanı, cache, message queue

# 5. Build, Release, Run - Ayrı aşamalar
# Build: Docker image oluştur
# Release: Konfigürasyon ile birleştir
# Run: Container'ı çalıştır

# 6. Processes - Stateless ve stateless işlemler
# Uygulama state'i dış servislerde sakla

# 7. Port Binding - Kendi port'unu export et
# Uygulama kendi port'unu dinlesin

# 8. Concurrency - Process modeli ile ölçeklendir
# Horizontal scaling için hazır ol

# 9. Disposability - Hızlı başlatma ve güvenli kapatma
# Graceful shutdown implement et

# 10. Dev/Prod Parity - Geliştirme ve production benzerliği
# Aynı araçları ve süreçleri kullan

# 11. Logs - Log'ları stdout'a yaz
# Log aggregation için hazır ol

# 12. Admin Processes - Admin işlemlerini tek seferlik yap
# Migration, backup gibi işlemler

Containerization

Docker Best Practices

# Multi-stage build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

Docker Compose

version: '3.8'
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgresql://user:pass@db:5432/app
    depends_on:
      - db
      - redis
  
  db:
    image: postgres:13
    environment:
      - POSTGRES_DB=app
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
    volumes:
      - postgres_data:/var/lib/postgresql/data
  
  redis:
    image: redis:6-alpine
    ports:
      - "6379:6379"

volumes:
  postgres_data:

Kubernetes Deployment

Deployment Configuration

apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloud-native-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: cloud-native-app
  template:
    metadata:
      labels:
        app: cloud-native-app
    spec:
      containers:
      - name: app
        image: cloud-native-app:latest
        ports:
        - containerPort: 3000
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: app-secrets
              key: database-url
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "256Mi"
            cpu: "200m"
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 3000
          initialDelaySeconds: 5
          periodSeconds: 5

Service Configuration

apiVersion: v1
kind: Service
metadata:
  name: cloud-native-app-service
spec:
  selector:
    app: cloud-native-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 3000
  type: LoadBalancer

CI/CD Pipeline

GitHub Actions

name: CI/CD Pipeline

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    
    - name: Setup Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Run tests
      run: npm test
    
    - name: Run linting
      run: npm run lint

  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    
    - name: Build Docker image
      run: docker build -t cloud-native-app:${{ github.sha }} .
    
    - name: Push to registry
      run: |
        echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
        docker push cloud-native-app:${{ github.sha }}

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    
    - name: Deploy to Kubernetes
      run: |
        kubectl set image deployment/cloud-native-app app=cloud-native-app:${{ github.sha }}

Monitoring ve Observability

Prometheus Configuration

apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-config
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
    scrape_configs:
      - job_name: 'cloud-native-app'
        static_configs:
          - targets: ['cloud-native-app-service:80']
        metrics_path: '/metrics'

Application Metrics

const prometheus = require('prom-client');

// Metrics
const httpRequestDuration = new prometheus.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'status_code']
});

const httpRequestTotal = new prometheus.Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
  labelNames: ['method', 'route', 'status_code']
});

// Middleware
app.use((req, res, next) => {
  const start = Date.now();
  
  res.on('finish', () => {
    const duration = (Date.now() - start) / 1000;
    httpRequestDuration
      .labels(req.method, req.route?.path || req.path, res.statusCode)
      .observe(duration);
    httpRequestTotal
      .labels(req.method, req.route?.path || req.path, res.statusCode)
      .inc();
  });
  
  next();
});

// Metrics endpoint
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', prometheus.register.contentType);
  res.end(await prometheus.register.metrics());
});

Security Best Practices

Container Security

# Non-root user
FROM node:18-alpine
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
USER nextjs

# Security scanning
# docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy image cloud-native-app:latest

Kubernetes Security

apiVersion: v1
kind: Pod
metadata:
  name: secure-app
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    fsGroup: 2000
  containers:
  - name: app
    image: cloud-native-app:latest
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL

Performance Optimization

Horizontal Pod Autoscaling

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: cloud-native-app-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: cloud-native-app
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

Sonuç

Cloud-native development, modern uygulama geliştirme için güçlü bir yaklaşımdır. Containerization, orchestration, CI/CD ve monitoring gibi teknolojileri kullanarak ölçeklenebilir, dayanıklı ve güvenli uygulamalar geliştirebilirsiniz.

Önerilen Araçlar

  • Container Runtime: Docker, containerd
  • Orchestration: Kubernetes, Docker Swarm
  • CI/CD: GitHub Actions, GitLab CI, Jenkins
  • Monitoring: Prometheus, Grafana, Jaeger
  • Service Mesh: Istio, Linkerd
  • API Gateway: Kong, AWS API Gateway

Bu Yazıyı Paylaş: