Golang Docker Kubernetes Deployment: E-Commerce Local to Staging Production
Setup Docker Compose dan Kubernetes untuk Santekno Shop. Multi-stage Docker build, Helm chart, health probes, resource limits, dan GitOps workflow dari local ke staging environment.
Melakukan deployment aplikasi Golang ecommerce dengan Docker dan Kubernetes adalah jembatan terakhir dari kode yang berjalan di laptop ke service yang bisa diakses publik. Aplikasi Santekno Shop sudah siap — sekarang kita containerize dan deploy. Di artikel ini kita bangun multi-stage Dockerfile untuk image minimal, docker-compose untuk development, Kubernetes manifests untuk staging, dan health probe yang sudah kita buat di Artikel 14.
15.01 Multi-Stage Dockerfile
Image Go yang naif bisa mencapai ratusan MB dan membawa seluruh toolchain ke production. Dockerfile multi-stage berikut memisahkan tahap build dari runtime sehingga image akhir hanya berisi binary di atas scratch.
1# Dockerfile
2
3# ════════════════════════════════════════
4# STAGE 1: Build
5# ════════════════════════════════════════
6FROM golang:1.22-alpine AS builder
7
8# Install build dependencies
9RUN apk add --no-cache git ca-certificates tzdata
10
11WORKDIR /app
12
13# Download dependencies first (layer cache)
14COPY go.mod go.sum ./
15RUN go mod download && go mod verify
16
17# Copy source code
18COPY . .
19
20# Build binary — statically linked, stripped symbols
21RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
22 go build \
23 -ldflags="-w -s -X main.version=${VERSION:-dev} -X main.buildTime=$(date -u +%Y%m%dT%H%M%SZ)" \
24 -trimpath \
25 -o /app/bin/server \
26 ./cmd/server/
27
28# ════════════════════════════════════════
29# STAGE 2: Runtime
30# ════════════════════════════════════════
31FROM scratch
32
33# Copy runtime dependencies
34COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
35COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
36COPY --from=builder /app/bin/server /server
37COPY --from=builder /app/migrations /migrations
38
39# Non-root user (UID 65534 = nobody)
40USER 65534:65534
41
42EXPOSE 8080
43
44# Health check (Kubernetes juga pakai ini)
45HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
46 CMD ["/server", "-health-check"]
47
48ENTRYPOINT ["/server"]Dengan FROM scratch, image runtime tidak punya shell maupun utilitas OS — hanya binary statically-linked, sehingga attack surface hampir nol. Menyalin ca-certificates dan zoneinfo tetap diperlukan agar TLS dan timezone berfungsi.
15.02 .dockerignore
Menyalin seluruh direktori ke build context memperlambat build dan bisa membocorkan file rahasia. File .dockerignore berikut mengecualikan file dev, test, dokumentasi, dan artefak build dari context.
1# .dockerignore
2
3# Development files
4.git
5.gitignore
6.env
7*.env.local
8*.env.development
9
10# Test files
11*_test.go
12testdata/
13testutil/
14
15# Documentation
16*.md
17docs/
18CLAUDE.md
19
20# Build artifacts
21tmp/
22coverage.out
23*.out
24
25# Scripts
26scripts/
27
28# IDE
29.idea/
30.vscode/
31
32# Docker files themselves
33Dockerfile*
34docker-compose*Mengecualikan .env dan CLAUDE.md mencegah kredensial dan konteks internal masuk ke image. Selain lebih aman, build context yang ramping juga mempercepat proses build secara signifikan.
15.03 Docker Compose: Development Full Stack
Development yang realistis butuh seluruh dependensi — Postgres, Redis, Kafka — berjalan bersama aplikasi. File docker-compose berikut mendefinisikan full stack development lengkap dengan healthcheck dan hot reload.
1# docker-compose.yml
2
3version: '3.8'
4
5services:
6 # ────────────────────────────────
7 # APPLICATION
8 # ────────────────────────────────
9 app:
10 build:
11 context: .
12 dockerfile: Dockerfile
13 target: builder # untuk dev: buat dari builder stage
14 command: air -c .air.toml # hot reload
15 ports:
16 - "8080:8080"
17 environment:
18 PORT: 8080
19 ENV: development
20 DATABASE_URL: postgres://postgres:postgres@postgres:5432/santekno_shop?sslmode=disable
21 REDIS_URL: redis:6379
22 KAFKA_BROKERS: kafka:29092
23 KAFKA_ENABLED: "true"
24 JWT_ACCESS_SECRET: dev-access-secret-min-32-chars-xxxxx
25 JWT_REFRESH_SECRET: dev-refresh-secret-min-32-chars-xxxx
26 PAYMENT_WEBHOOK_SECRET: dev-webhook-secret-min-32-chars-xx
27 volumes:
28 - .:/app # mount source untuk hot reload
29 - go-cache:/root/go # Go module cache
30 depends_on:
31 postgres:
32 condition: service_healthy
33 redis:
34 condition: service_healthy
35 kafka:
36 condition: service_healthy
37
38 # ────────────────────────────────
39 # DATABASE
40 # ────────────────────────────────
41 postgres:
42 image: pgvector/pgvector:pg15
43 environment:
44 POSTGRES_DB: santekno_shop
45 POSTGRES_USER: postgres
46 POSTGRES_PASSWORD: postgres
47 ports:
48 - "5432:5432"
49 volumes:
50 - postgres-data:/var/lib/postgresql/data
51 healthcheck:
52 test: ["CMD-SHELL", "pg_isready -U postgres -d santekno_shop"]
53 interval: 5s
54 timeout: 5s
55 retries: 10
56
57 # ────────────────────────────────
58 # CACHE
59 # ────────────────────────────────
60 redis:
61 image: redis:7-alpine
62 command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru
63 ports:
64 - "6379:6379"
65 volumes:
66 - redis-data:/data
67 healthcheck:
68 test: ["CMD", "redis-cli", "ping"]
69 interval: 5s
70 timeout: 3s
71 retries: 5
72
73 # ────────────────────────────────
74 # MESSAGING
75 # ────────────────────────────────
76 zookeeper:
77 image: confluentinc/cp-zookeeper:7.5.0
78 environment:
79 ZOOKEEPER_CLIENT_PORT: 2181
80 healthcheck:
81 test: echo stat | nc localhost 2181
82 interval: 10s
83
84 kafka:
85 image: confluentinc/cp-kafka:7.5.0
86 depends_on:
87 zookeeper:
88 condition: service_healthy
89 environment:
90 KAFKA_BROKER_ID: 1
91 KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
92 KAFKA_LISTENERS: INTERNAL://0.0.0.0:29092,EXTERNAL://0.0.0.0:9092
93 KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://localhost:9092
94 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
95 KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
96 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
97 KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
98 ports:
99 - "9092:9092"
100 healthcheck:
101 test: kafka-topics --bootstrap-server localhost:9092 --list
102 interval: 10s
103 timeout: 10s
104 retries: 10
105
106 # ────────────────────────────────
107 # DEVELOPMENT TOOLS
108 # ────────────────────────────────
109 kafka-ui:
110 image: provectuslabs/kafka-ui:latest
111 ports:
112 - "8090:8080"
113 environment:
114 KAFKA_CLUSTERS_0_NAME: local
115 KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:29092
116 depends_on:
117 - kafka
118
119 mailhog:
120 image: mailhog/mailhog
121 ports:
122 - "1025:1025" # SMTP
123 - "8025:8025" # Web UI
124
125 adminer:
126 image: adminer
127 ports:
128 - "8082:8080"
129 depends_on:
130 - postgres
131
132volumes:
133 postgres-data:
134 redis-data:
135 go-cache:Kunci dari setup ini adalah depends_on dengan condition: service_healthy yang memastikan aplikasi hanya start setelah semua dependensi benar-benar siap. Satu perintah docker-compose up -d cukup untuk menyalakan seluruh environment development.
15.04 docker-compose.test.yml
Integration test butuh database dan cache yang terisolasi dari environment development. File compose berikut menyediakan Postgres dan Redis khusus test di port berbeda agar tidak bentrok dengan dev.
1# docker-compose.test.yml — untuk integration tests
2
3version: '3.8'
4
5services:
6 postgres-test:
7 image: pgvector/pgvector:pg15
8 environment:
9 POSTGRES_DB: santekno_test
10 POSTGRES_USER: testuser
11 POSTGRES_PASSWORD: testpass
12 ports:
13 - "5433:5432" # port berbeda dari dev postgres
14 healthcheck:
15 test: ["CMD-SHELL", "pg_isready -U testuser -d santekno_test"]
16 interval: 3s
17 retries: 10
18
19 redis-test:
20 image: redis:7-alpine
21 ports:
22 - "6380:6379" # port berbeda dari dev redis
23
24# Makefile:
25# test-integration:
26# docker-compose -f docker-compose.test.yml up -d
27# DATABASE_URL="postgres://testuser:testpass@localhost:5433/santekno_test" \
28# REDIS_URL="localhost:6380" \
29# go test -tags integration ./...
30# docker-compose -f docker-compose.test.yml downPort 5433 dan 6380 sengaja berbeda dari dev supaya kamu bisa menjalankan integration test tanpa mengganggu data development yang sedang dipakai. Target Makefile di komentar menunjukkan siklus lengkap: up, test, down.
15.05 Kubernetes: Namespace dan ConfigMap
Di Kubernetes, konfigurasi non-sensitif dipisah dari kode lewat ConfigMap dan diisolasi dengan namespace. Manifest berikut mendefinisikan namespace santekno-shop beserta ConfigMap untuk pengaturan seperti port, log level, dan pool DB.
1# k8s/base/namespace.yaml
2
3apiVersion: v1
4kind: Namespace
5metadata:
6 name: santekno-shop
7 labels:
8 app.kubernetes.io/managed-by: kubectl
9 environment: stagingNamespace di atas mengisolasi seluruh resource aplikasi dalam satu lingkup. Selanjutnya ConfigMap berikut menyimpan konfigurasi non-rahasia yang dipakai oleh Pod.
1# k8s/base/configmap.yaml
2
3apiVersion: v1
4kind: ConfigMap
5metadata:
6 name: santekno-shop-config
7 namespace: santekno-shop
8data:
9 PORT: "8080"
10 ENV: "staging"
11 LOG_LEVEL: "info"
12 KAFKA_BROKERS: "kafka-service:9092"
13 KAFKA_ENABLED: "true"
14 KAFKA_GROUP_ID: "santekno-notification"
15 DB_MAX_OPEN_CONNS: "25"
16 DB_MAX_IDLE_CONNS: "5"Namespace memberi isolasi logis sehingga resource staging tidak tercampur dengan environment lain di cluster yang sama. ConfigMap hanya menampung nilai non-sensitif — kredensial akan ditangani terpisah lewat Secret.
15.06 Kubernetes: Secrets
Data sensitif seperti DATABASE_URL dan JWT secret tidak boleh masuk ConfigMap apalagi di-commit ke Git. Manifest Secret berikut menampung kredensial tersebut, dengan catatan tegas untuk memakai secret manager di production.
1# k8s/base/secrets.yaml
2# JANGAN commit file ini ke repo!
3# Gunakan: kubectl create secret atau Sealed Secrets / External Secrets
4
5apiVersion: v1
6kind: Secret
7metadata:
8 name: santekno-shop-secrets
9 namespace: santekno-shop
10type: Opaque
11stringData:
12 DATABASE_URL: "postgres://user:pass@postgres-service:5432/santekno_prod?sslmode=require"
13 REDIS_URL: "redis-service:6379"
14 JWT_ACCESS_SECRET: "your-32-char-min-access-secret"
15 JWT_REFRESH_SECRET: "your-32-char-min-refresh-secret"
16 PAYMENT_WEBHOOK_SECRET: "your-32-char-min-webhook-secret"
17 SMTP_HOST: "smtp.provider.com"
18 SMTP_PASSWORD: "smtp-password"
19
20# Best practice untuk production:
21# Gunakan HashiCorp Vault atau AWS Secrets Manager
22# Dengan External Secrets Operator untuk sync ke K8s secretsIngat bahwa base64 di K8s Secret bukan enkripsi — untuk production wajib pakai External Secrets Operator dengan Vault atau AWS Secrets Manager. Perlakukan file ini sebagai template lokal, jangan pernah masuk version control.
15.07 Kubernetes: Deployment
Deployment adalah inti dari menjalankan aplikasi di Kubernetes: berapa replica, resource limit, probe, dan strategi update. Manifest berikut mengonfigurasi rolling update zero-downtime dengan security context non-root dan health probe.
1# k8s/base/deployment.yaml
2
3apiVersion: apps/v1
4kind: Deployment
5metadata:
6 name: santekno-shop
7 namespace: santekno-shop
8 labels:
9 app: santekno-shop
10 version: "1.0.0"
11spec:
12 replicas: 2
13 selector:
14 matchLabels:
15 app: santekno-shop
16 strategy:
17 type: RollingUpdate
18 rollingUpdate:
19 maxSurge: 1 # satu pod tambahan saat update
20 maxUnavailable: 0 # zero downtime deployment
21 template:
22 metadata:
23 labels:
24 app: santekno-shop
25 annotations:
26 prometheus.io/scrape: "true"
27 prometheus.io/port: "8080"
28 prometheus.io/path: "/metrics"
29 spec:
30 # Security context
31 securityContext:
32 runAsNonRoot: true
33 runAsUser: 65534 # nobody
34 fsGroup: 65534
35
36 containers:
37 - name: santekno-shop
38 image: registry.santekno.com/santekno-shop:${IMAGE_TAG}
39 imagePullPolicy: Always
40 ports:
41 - containerPort: 8080
42 name: http
43
44 # Environment dari ConfigMap dan Secret
45 envFrom:
46 - configMapRef:
47 name: santekno-shop-config
48 - secretRef:
49 name: santekno-shop-secrets
50
51 # Resource limits — penting untuk K8s scheduling
52 resources:
53 requests:
54 cpu: "100m" # 0.1 CPU
55 memory: "128Mi"
56 limits:
57 cpu: "500m" # 0.5 CPU
58 memory: "512Mi"
59
60 # Liveness probe: restart jika tidak responsif
61 livenessProbe:
62 httpGet:
63 path: /health
64 port: 8080
65 initialDelaySeconds: 15
66 periodSeconds: 30
67 timeoutSeconds: 5
68 failureThreshold: 3
69
70 # Readiness probe: remove dari LB jika DB tidak tersedia
71 readinessProbe:
72 httpGet:
73 path: /ready
74 port: 8080
75 initialDelaySeconds: 10
76 periodSeconds: 10
77 timeoutSeconds: 5
78 failureThreshold: 3
79
80 # Graceful shutdown
81 lifecycle:
82 preStop:
83 exec:
84 command: ["/bin/sh", "-c", "sleep 5"]
85 # 5 detik untuk in-flight requests selesai sebelum SIGTERM
86
87 # Terminate dengan grace period 30 detik
88 terminationGracePeriodSeconds: 30
89
90 # Image pull secret jika registry private
91 imagePullSecrets:
92 - name: registry-credentialsKombinasi maxUnavailable: 0 dengan readiness probe menghasilkan zero-downtime: pod lama tidak dihapus sebelum pod baru lolos readiness check. Resource requests/limits juga wajib supaya scheduler bisa menempatkan pod dengan benar dan mencegah satu pod melahap seluruh node.
15.08 Kubernetes: Service dan Ingress
Pod bersifat efemeral, jadi traffic harus masuk lewat Service (internal) dan Ingress (eksternal dengan TLS). Manifest berikut mengekspos aplikasi via ClusterIP Service dan Ingress nginx dengan sertifikat Let’s Encrypt.
1# k8s/base/service.yaml
2
3apiVersion: v1
4kind: Service
5metadata:
6 name: santekno-shop-service
7 namespace: santekno-shop
8spec:
9 type: ClusterIP # internal service, diakses via Ingress
10 selector:
11 app: santekno-shop
12 ports:
13 - port: 80
14 targetPort: 8080
15 protocol: TCP
16 name: httpService di atas mengekspos Pod secara internal di dalam cluster. Ingress berikut kemudian merutekan trafik eksternal HTTPS menuju Service tersebut.
1# k8s/base/ingress.yaml
2
3apiVersion: networking.k8s.io/v1
4kind: Ingress
5metadata:
6 name: santekno-shop-ingress
7 namespace: santekno-shop
8 annotations:
9 kubernetes.io/ingress.class: nginx
10 cert-manager.io/cluster-issuer: letsencrypt-prod
11 nginx.ingress.kubernetes.io/proxy-read-timeout: "30"
12 nginx.ingress.kubernetes.io/proxy-body-size: "10m"
13 # Rate limiting di Ingress level (tambahan dari app level)
14 nginx.ingress.kubernetes.io/limit-rps: "100"
15spec:
16 tls:
17 - hosts:
18 - api.staging.santekno.com
19 secretName: santekno-tls-staging
20 rules:
21 - host: api.staging.santekno.com
22 http:
23 paths:
24 - path: /
25 pathType: Prefix
26 backend:
27 service:
28 name: santekno-shop-service
29 port:
30 number: 80Service memberi alamat stabil ke sekumpulan pod yang berubah-ubah, sementara Ingress menangani TLS dan routing domain api.staging.santekno.com. Rate limit di level Ingress bersifat komplemen terhadap rate limit aplikasi yang kita bangun di Artikel 14.
15.09 Kubernetes: HorizontalPodAutoscaler
Traffic ecommerce naik-turun, jadi jumlah pod harus otomatis menyesuaikan beban. Manifest HPA berikut menskalakan pod antara 2 hingga 10 berdasarkan utilisasi CPU dan memory, lengkap dengan kebijakan stabilisasi.
1# k8s/base/hpa.yaml
2
3apiVersion: autoscaling/v2
4kind: HorizontalPodAutoscaler
5metadata:
6 name: santekno-shop-hpa
7 namespace: santekno-shop
8spec:
9 scaleTargetRef:
10 apiVersion: apps/v1
11 kind: Deployment
12 name: santekno-shop
13 minReplicas: 2
14 maxReplicas: 10
15 metrics:
16 - type: Resource
17 resource:
18 name: cpu
19 target:
20 type: Utilization
21 averageUtilization: 70 # scale up jika CPU > 70%
22 - type: Resource
23 resource:
24 name: memory
25 target:
26 type: Utilization
27 averageUtilization: 80 # scale up jika memory > 80%
28 behavior:
29 scaleUp:
30 stabilizationWindowSeconds: 60 # tunggu 1 menit sebelum scale up lagi
31 policies:
32 - type: Pods
33 value: 2 # tambah max 2 pod sekaligus
34 periodSeconds: 60
35 scaleDown:
36 stabilizationWindowSeconds: 300 # tunggu 5 menit sebelum scale downStabilization window yang berbeda untuk scale up (60 detik) dan scale down (300 detik) mencegah flapping — pod tidak dibuang terlalu cepat saat traffic sesaat turun. HPA hanya bekerja jika resource requests di deployment sudah di-set, karena utilisasi dihitung relatif terhadapnya.
15.10 Database Migration di Kubernetes
Migrasi database harus berjalan sebelum versi aplikasi baru menerima traffic. Manifest Job dan snippet Makefile berikut menjalankan migrasi sebagai Job terpisah lalu rolling update deployment setelah migrasi sukses.
1# k8s/jobs/migration.yaml
2# Run SEBELUM deployment update
3
4apiVersion: batch/v1
5kind: Job
6metadata:
7 name: db-migration-${VERSION}
8 namespace: santekno-shop
9spec:
10 ttlSecondsAfterFinished: 3600 # hapus job setelah 1 jam
11 template:
12 spec:
13 restartPolicy: Never
14 containers:
15 - name: migration
16 image: registry.santekno.com/santekno-shop:${IMAGE_TAG}
17 command: ["/server", "-migrate"]
18 envFrom:
19 - secretRef:
20 name: santekno-shop-secrets
21 resources:
22 requests:
23 cpu: "100m"
24 memory: "64Mi"
25 imagePullSecrets:
26 - name: registry-credentialsJob migrasi di atas dijalankan sekali untuk menyiapkan skema database sebelum rilis. Makefile target berikut mengotomasi urutan build image, menjalankan migrasi, lalu rolling update deployment.
1# Makefile target untuk deploy:
2deploy-staging:
3 # 1. Build dan push image
4 docker build --build-arg VERSION=$(git describe --tags) -t registry.santekno.com/santekno-shop:$(git rev-parse --short HEAD) .
5 docker push registry.santekno.com/santekno-shop:$(git rev-parse --short HEAD)
6
7 # 2. Run migration job (tunggu selesai)
8 kubectl apply -f k8s/jobs/migration.yaml
9 kubectl wait --for=condition=complete job/db-migration-${VERSION} --timeout=120s -n santekno-shop
10
11 # 3. Rolling update deployment
12 kubectl set image deployment/santekno-shop \
13 santekno-shop=registry.santekno.com/santekno-shop:$(git rev-parse --short HEAD) \
14 -n santekno-shop
15
16 # 4. Verify rollout
17 kubectl rollout status deployment/santekno-shop -n santekno-shopMenjalankan migrasi sebagai Job dengan kubectl wait memastikan deployment baru tidak dimulai jika skema database gagal diperbarui. ttlSecondsAfterFinished otomatis membersihkan Job lama supaya cluster tidak menumpuk objek Job.
15.11 GitHub Actions: CI/CD Pipeline untuk Staging
Deploy manual rawan error, jadi seluruh alur dari test hingga smoke test harus otomatis. Workflow GitHub Actions berikut menjalankan test, build image, migrasi, rolling deploy, smoke test, dan notifikasi Slack setiap push ke branch develop.
1# .github/workflows/deploy-staging.yml
2
3name: Deploy to Staging
4
5on:
6 push:
7 branches: [develop]
8
9env:
10 REGISTRY: registry.santekno.com
11 IMAGE_NAME: santekno-shop
12
13jobs:
14 test:
15 uses: ./.github/workflows/ci.yml # reuse CI workflow dari Artikel 04
16
17 build-and-push:
18 needs: test
19 runs-on: ubuntu-latest
20 outputs:
21 image-tag: ${{ steps.meta.outputs.tags }}
22 steps:
23 - uses: actions/checkout@v4
24
25 - name: Docker meta
26 id: meta
27 uses: docker/metadata-action@v5
28 with:
29 images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
30 tags: |
31 type=sha,prefix=,suffix=,format=short
32 type=ref,event=branch
33 type=raw,value=latest,enable={{is_default_branch}}
34
35 - name: Login to registry
36 uses: docker/login-action@v3
37 with:
38 registry: ${{ env.REGISTRY }}
39 username: ${{ secrets.REGISTRY_USERNAME }}
40 password: ${{ secrets.REGISTRY_PASSWORD }}
41
42 - name: Build and push
43 uses: docker/build-push-action@v5
44 with:
45 context: .
46 push: true
47 tags: ${{ steps.meta.outputs.tags }}
48 cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
49 cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max
50 build-args: VERSION=${{ github.sha }}
51
52 deploy-staging:
53 needs: build-and-push
54 runs-on: ubuntu-latest
55 environment: staging
56 steps:
57 - uses: actions/checkout@v4
58
59 - name: Setup kubectl
60 uses: azure/setup-kubectl@v3
61
62 - name: Configure kubeconfig
63 run: echo "${{ secrets.KUBE_CONFIG_STAGING }}" | base64 -d > ~/.kube/config
64
65 - name: Run database migration
66 run: |
67 export IMAGE_TAG=${{ github.sha }}
68 export VERSION=${{ github.sha }}
69 envsubst < k8s/jobs/migration.yaml | kubectl apply -f -
70 kubectl wait --for=condition=complete \
71 job/db-migration-${VERSION:0:7} \
72 --timeout=120s -n santekno-shop
73
74 - name: Deploy application
75 run: |
76 kubectl set image deployment/santekno-shop \
77 santekno-shop=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \
78 -n santekno-shop
79 kubectl rollout status deployment/santekno-shop \
80 -n santekno-shop --timeout=300s
81
82 - name: Smoke test
83 run: |
84 STAGING_URL="https://api.staging.santekno.com"
85 sleep 30 # tunggu pods ready
86
87 # Health check
88 curl -f "$STAGING_URL/health" || { echo "Health check failed"; exit 1; }
89
90 # Basic API check
91 curl -f "$STAGING_URL/api/v1/products" || { echo "Products API failed"; exit 1; }
92
93 echo "Smoke test passed"
94
95 - name: Notify
96 if: always()
97 uses: 8398a7/action-slack@v3
98 with:
99 status: ${{ job.status }}
100 text: "Staging deployment ${{ job.status }}: ${{ github.sha }}"
101 webhook_url: ${{ secrets.SLACK_WEBHOOK }}Pipeline ini menerapkan gate berlapis: test harus lulus sebelum build, migrasi harus sukses sebelum deploy, dan smoke test memverifikasi bahwa staging benar-benar melayani request. Caching layer registry membuat build image berikutnya jauh lebih cepat.
15.12 Rollback Strategy
Deploy yang bermasalah harus bisa dibalik dalam hitungan detik. Perintah berikut menunjukkan cara melihat history, rollback ke revisi sebelumnya atau spesifik, dan menangani migrasi database jika perlu dibalik.
1# Rollback deployment jika ada masalah
2
3# Lihat revision history
4kubectl rollout history deployment/santekno-shop -n santekno-shop
5
6# Rollback ke versi sebelumnya
7kubectl rollout undo deployment/santekno-shop -n santekno-shop
8
9# Rollback ke revision spesifik
10kubectl rollout undo deployment/santekno-shop \
11 --to-revision=3 -n santekno-shop
12
13# Verify rollback
14kubectl rollout status deployment/santekno-shop -n santekno-shop
15
16# Jika database migration sudah applied:
17# Gunakan down migration
18migrate -path ./migrations -database "$DATABASE_URL" down 1Rollback deployment bersifat instan karena Kubernetes menyimpan revisi lama, tapi migrasi database perlu perhatian khusus — down migration hanya aman jika perubahannya reversible. Rancang migrasi additive supaya rollback aplikasi tidak mengharuskan rollback skema.
15.13 Resource Sizing
Menentukan berapa pod dan resource yang dibutuhkan sebaiknya berbasis estimasi, bukan tebakan. Perhitungan berikut menurunkan kebutuhan resource Santekno Shop dari target 100K MAU dan 10K order per hari.
1Santekno Shop resource estimates:
2
3Target: 100K MAU, 10K orders/day
4
5Request rate:
6 Peak: ~100 RPS (assumptions: 10K orders/day, spiky)
7 Average: ~10 RPS
8
9Per-pod capacity:
10 1 pod handles ~50 RPS (conservative estimate)
11 Memory: ~128MB RSS (Go binary + heap)
12 CPU: ~100m average, ~500m peak
13
14Sizing:
15 Staging: 2 pods (replicas: 2)
16 Production: 4 pods minimum, HPA up to 10
17
18Database:
19 PostgreSQL: db.t3.medium (2 vCPU, 4GB) → adequate untuk 100K MAU
20
21Cache:
22 Redis: cache.t3.micro (1 vCPU, 0.5GB) → adequate
23
24Kafka:
25 3 brokers, 3 partitions per topic → adequate untuk 10K orders/day
26
27Load testing (Artikel 19 — Part 4):
28 k6 akan validate assumptions iniEstimasi ini bersifat asumsi awal yang harus divalidasi dengan load test nyata di Artikel 19 — angka konservatif “1 pod ~50 RPS” memberi ruang aman. Yang penting: sizing punya dasar perhitungan, bukan sekadar menaikkan replica saat ada masalah.
15.14 Local Kubernetes dengan kind
Sebelum menyentuh cluster staging, manifest sebaiknya diuji di Kubernetes lokal. Perintah berikut membuat cluster kind dengan port mapping, memuat image lokal, dan meng-apply manifest untuk verifikasi cepat.
1# Development Kubernetes cluster dengan kind (Kubernetes in Docker)
2brew install kind
3
4# Buat cluster
5kind create cluster --config - << 'EOF'
6kind: Cluster
7apiVersion: kind.x-k8s.io/v1alpha4
8nodes:
9 - role: control-plane
10 extraPortMappings:
11 - containerPort: 30080
12 hostPort: 8080
13 protocol: TCP
14EOF
15
16# Load local Docker image ke kind
17kind load docker-image registry.santekno.com/santekno-shop:latest
18
19# Apply manifests
20kubectl apply -f k8s/base/
21
22# Verify
23kubectl get pods -n santekno-shop
24kubectl logs -l app=santekno-shop -n santekno-shopDengan kind, kamu bisa memvalidasi seluruh manifest — deployment, service, probe — di laptop tanpa biaya cloud. Ini menangkap kesalahan YAML dan konfigurasi jauh sebelum pipeline menyentuh staging.
15.15 Docker Image Size Optimization
Ukuran image berdampak langsung ke kecepatan pull dan attack surface. Perintah berikut menunjukkan hasil multi-stage build dan cara memverifikasi ukuran, memindai kerentanan, serta menganalisis layer.
1# Hasil dari multi-stage build:
2# Stage builder: ~1.5GB (golang:1.22-alpine dengan semua deps)
3# Stage runtime: ~20MB (scratch + binary)
4# Perbedaan: 98.7% lebih kecil!
5
6# Verify image size:
7docker images | grep santekno-shop
8# santekno-shop latest abc123def456 2 minutes ago 21.3MB
9
10# Scan vulnerabilities:
11trivy image santekno-shop:latest
12
13# Layer analysis:
14dive santekno-shop:latestReduksi dari 1.5GB ke sekitar 21MB bukan sekadar angka — image kecil berarti pull lebih cepat, cold start lebih singkat, dan lebih sedikit CVE untuk ditambal. Jadikan trivy bagian dari pipeline supaya kerentanan tertangkap sebelum image sampai production.
15.16 ConfigMap vs Secret: Guidelines
Salah menaruh kredensial di ConfigMap adalah kesalahan keamanan yang umum. Panduan berikut menegaskan apa yang boleh masuk ConfigMap versus Secret, beserta praktik terbaik pengelolaan secret.
1ConfigMap:
2 PORT, ENV, LOG_LEVEL
3 KAFKA_BROKERS (tidak sensitive)
4 DB_MAX_OPEN_CONNS
5 Feature flags
6 Jangan: DATABASE_URL, passwords, API keys
7
8Secret:
9 DATABASE_URL (mengandung password)
10 JWT_ACCESS_SECRET, JWT_REFRESH_SECRET
11 PAYMENT_WEBHOOK_SECRET
12 SMTP_PASSWORD
13 API keys untuk payment gateway
14
15Best practices:
16 - Gunakan External Secrets Operator (ESO) + HashiCorp Vault atau AWS SM
17 - Jangan base64-encode secrets di Git (itu bukan encryption!)
18 - Rotate secrets secara berkala
19 - Audit access ke secretsAturan sederhananya: apa pun yang bisa dipakai untuk mengakses sistem lain adalah Secret, sisanya ConfigMap. Ingat kembali bahwa base64 bukan enkripsi — untuk production, sinkronkan secret dari Vault atau AWS Secrets Manager lewat ESO.
15.17 Staging Environment Checklist
Sebuah staging dianggap “ready” hanya jika seluruh aspek infrastruktur, aplikasi, monitoring, dan keamanan terpenuhi. Checklist berikut merangkum semua yang harus dicek sebelum staging deploy dinyatakan lolos.
1Sebelum staging deploy dianggap "ready":
2
3Infrastructure:
4□ PostgreSQL 15 dengan pgvector extension
5□ Redis 7 dengan persistence
6□ Kafka cluster dengan 3 partitions per topic
7□ TLS certificate (Let's Encrypt via cert-manager)
8□ Ingress controller (nginx)
9
10Application:
11□ Health endpoint return 200 (/health)
12□ Readiness endpoint return 200 (/ready) — DB dan Redis connected
13□ GET /api/v1/products return products dari seed data
14□ POST /api/v1/auth/register berfungsi
15□ POST /api/v1/auth/login berfungsi
16□ Swagger UI accessible (opsional)
17
18Monitoring:
19□ Prometheus scraping /metrics
20□ Grafana dashboard ada
21□ Alert rules configured (Artikel 18 — Part 4)
22□ Log aggregation (Loki atau CloudWatch)
23
24Security:
25□ Secrets tidak di Git
26□ Security headers present (curl -I https://api.staging.santekno.com)
27□ TLS 1.2+ only
28□ Non-root containerChecklist ini memaksa verifikasi menyeluruh alih-alih mengandalkan “sepertinya sudah jalan”. Simpan sebagai template yang dicentang setiap kali menyiapkan atau meninjau ulang environment staging.
15.18 Database di Kubernetes
Untuk staging, Postgres bisa dijalankan di dalam cluster sebagai StatefulSet dengan persistent volume. Manifest berikut menunjukkan setup tersebut, sekaligus menegaskan bahwa production sebaiknya memakai managed database.
1# Untuk staging: PostgreSQL sebagai StatefulSet
2
3apiVersion: apps/v1
4kind: StatefulSet
5metadata:
6 name: postgres
7 namespace: santekno-shop
8spec:
9 replicas: 1
10 serviceName: postgres-service
11 selector:
12 matchLabels:
13 app: postgres
14 template:
15 spec:
16 containers:
17 - name: postgres
18 image: pgvector/pgvector:pg15
19 env:
20 - name: POSTGRES_DB
21 value: santekno_prod
22 - name: POSTGRES_PASSWORD
23 valueFrom:
24 secretKeyRef:
25 name: postgres-secret
26 key: password
27 volumeMounts:
28 - name: postgres-data
29 mountPath: /var/lib/postgresql/data
30 volumeClaimTemplates:
31 - metadata:
32 name: postgres-data
33 spec:
34 accessModes: ["ReadWriteOnce"]
35 resources:
36 requests:
37 storage: 20Gi
38
39# Production: gunakan managed database (RDS, Cloud SQL)
40# Lebih reliable, backups otomatis, failover otomatisStatefulSet dengan volumeClaimTemplates memberi Postgres identitas stabil dan storage persisten yang tidak hilang saat pod restart. Untuk staging ini cukup, tapi di production managed database (RDS/Cloud SQL) jauh lebih andal karena menangani backup dan failover otomatis.
15.19 Kustomize: Base dan Overlay
Staging dan production berbagi banyak manifest tapi berbeda di beberapa nilai seperti jumlah replica. Struktur Kustomize berikut memisahkan base yang dipakai bersama dari overlay per-environment.
1k8s/
2├── base/
3│ ├── namespace.yaml
4│ ├── configmap.yaml
5│ ├── deployment.yaml
6│ ├── service.yaml
7│ ├── hpa.yaml
8│ └── kustomization.yaml
9│
10├── overlays/
11│ ├── staging/
12│ │ ├── kustomization.yaml → replicas: 2, staging ingress
13│ │ └── patch-replicas.yaml
14│ │
15│ └── production/ → Topik 10
16│ ├── kustomization.yaml → replicas: 4, prod ingress, resource limits
17│ └── patch-resources.yamlStruktur direktori di atas memisahkan manifest base dari overlay per-environment. File kustomization staging berikut menunjukkan bagaimana overlay menimpa base dengan replicas dan ingress khusus staging.
1# k8s/overlays/staging/kustomization.yaml
2apiVersion: kustomize.config.k8s.io/v1beta1
3kind: Kustomization
4
5resources:
6 - ../../base
7
8namespace: santekno-shop
9
10images:
11 - name: registry.santekno.com/santekno-shop
12 newTag: ${IMAGE_TAG}
13
14patches:
15 - path: patch-replicas.yaml
16 target:
17 kind: Deployment
18 name: santekno-shopDengan pola base + overlay, satu perubahan di base otomatis berlaku ke semua environment sementara perbedaan spesifik dikelola lewat patch. Ini menghilangkan duplikasi manifest yang rawan drift antara staging dan production.
15.20 Ringkasan: Part 3 Selesai
Infrastruktur Santekno Shop sekarang siap dari local development sampai staging:
Dockerfile: multi-stage, FROM scratch, binary ~20MB, non-root user.
docker-compose: full development stack (app + postgres + redis + kafka + tools), hot reload dengan air.
Kubernetes manifests: namespace, configmap, secret, deployment (rolling update, zero downtime), service, ingress, HPA.
CI/CD: GitHub Actions push-to-develop → test → build image → migration job → rolling deploy → smoke test.
Database migration: Kubernetes Job yang berjalan sebelum deployment update.
Health probes: liveness (/health) dan readiness (/ready) dengan timeout yang tepat.
Dengan ini Part 3 selesai — kelima artikel infrastruktur (database migrations, Kafka integration, Redis caching, API Gateway, Docker + Kubernetes) sudah lengkap. Part 4 (Artikel 16-20) akan masuk ke Production Baseline: testing strategy, CI/CD dengan AI quality gates, observability, performance baseline, dan bridge ke Topik 6. Langkah pertama Part 4 adalah menyusun strategi testing yang menurunkan spec menjadi unit, integration, dan E2E test.