Golang Docker Kubernetes Deployment: E-Commerce Local to Staging Production
Setting up Docker Compose and Kubernetes for Santekno Shop. Multi-stage Docker build, Helm chart, health probes, resource limits, and a GitOps workflow from local to the staging environment.
Deploying a Golang ecommerce application with Docker and Kubernetes is the final bridge from code running on a laptop to a service the public can access. The Santekno Shop application is ready — now we containerize and deploy it. In this article we build a multi-stage Dockerfile for a minimal image, docker-compose for development, Kubernetes manifests for staging, and the health probes we created in Article 14.
15.01 Multi-Stage Dockerfile
A naive Go image can reach hundreds of MB and drag the entire toolchain into production. The multi-stage Dockerfile below separates the build stage from the runtime so the final image contains only the binary on top of 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 also uses this)
45HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
46 CMD ["/server", "-health-check"]
47
48ENTRYPOINT ["/server"]With FROM scratch, the runtime image has no shell or OS utilities — only the statically-linked binary, so the attack surface is almost zero. Copying ca-certificates and zoneinfo is still required for TLS and timezones to work.
15.02 .dockerignore
Copying the entire directory into the build context slows the build and can leak secret files. The .dockerignore file below excludes dev, test, documentation, and build artifact files from the 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*Excluding .env and CLAUDE.md prevents credentials and internal context from getting into the image. Besides being safer, a lean build context also speeds up the build process significantly.
15.03 Docker Compose: Development Full Stack
Realistic development needs the entire set of dependencies — Postgres, Redis, Kafka — running alongside the application. The docker-compose file below defines the full development stack, complete with healthchecks and 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 # for dev: build from the 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 for 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:The key to this setup is depends_on with condition: service_healthy, which ensures the application only starts after all dependencies are truly ready. A single docker-compose up -d command is enough to bring up the entire development environment.
15.04 docker-compose.test.yml
Integration tests need a database and cache isolated from the development environment. The compose file below provides a Postgres and Redis dedicated to testing on different ports so they don’t clash with dev.
1# docker-compose.test.yml — for 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" # different port from 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" # different port from 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 downPorts 5433 and 6380 are deliberately different from dev so you can run integration tests without disturbing the development data currently in use. The Makefile target in the comment shows the full cycle: up, test, down.
15.05 Kubernetes: Namespace and ConfigMap
In Kubernetes, non-sensitive configuration is separated from the code via a ConfigMap and isolated with a namespace. The manifests below define the santekno-shop namespace along with a ConfigMap for settings like port, log level, and DB pool.
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: stagingThe Namespace above isolates all application resources within a single scope. Next, the ConfigMap below stores the non-secret configuration consumed by the Pods.
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"The namespace provides logical isolation so staging resources don’t get mixed with other environments in the same cluster. The ConfigMap only holds non-sensitive values — credentials will be handled separately via a Secret.
15.06 Kubernetes: Secrets
Sensitive data like DATABASE_URL and JWT secrets must not go into a ConfigMap, let alone be committed to Git. The Secret manifest below holds those credentials, with a firm note to use a secret manager in production.
1# k8s/base/secrets.yaml
2# DO NOT commit this file to the repo!
3# Use: kubectl create secret or 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 for production:
21# Use HashiCorp Vault or AWS Secrets Manager
22# With the External Secrets Operator to sync into K8s secretsRemember that base64 in a K8s Secret is not encryption — for production you must use the External Secrets Operator with Vault or AWS Secrets Manager. Treat this file as a local template, and never let it enter version control.
15.07 Kubernetes: Deployment
The Deployment is the core of running an application on Kubernetes: how many replicas, resource limits, probes, and update strategy. The manifest below configures a zero-downtime rolling update with a non-root security context and health probes.
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 # one extra pod during 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 from ConfigMap and Secret
45 envFrom:
46 - configMapRef:
47 name: santekno-shop-config
48 - secretRef:
49 name: santekno-shop-secrets
50
51 # Resource limits — important for 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 if not responsive
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 from the LB if the DB is unavailable
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 seconds for in-flight requests to finish before SIGTERM
86
87 # Terminate with a 30-second grace period
88 terminationGracePeriodSeconds: 30
89
90 # Image pull secret if the registry is private
91 imagePullSecrets:
92 - name: registry-credentialsThe combination of maxUnavailable: 0 with the readiness probe produces zero-downtime: the old pod isn’t removed before the new pod passes the readiness check. Resource requests/limits are also mandatory so the scheduler can place the pod correctly and prevent one pod from devouring the whole node.
15.08 Kubernetes: Service and Ingress
Pods are ephemeral, so traffic must come in via a Service (internal) and an Ingress (external with TLS). The manifests below expose the application via a ClusterIP Service and an nginx Ingress with a Let’s Encrypt certificate.
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, accessed via Ingress
10 selector:
11 app: santekno-shop
12 ports:
13 - port: 80
14 targetPort: 8080
15 protocol: TCP
16 name: httpThe Service above exposes the Pods internally within the cluster. The Ingress below then routes external HTTPS traffic to that Service.
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 at the Ingress level (on top of the 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: 80The Service gives a stable address to a constantly-changing set of pods, while the Ingress handles TLS and routing for the api.staging.santekno.com domain. Rate limiting at the Ingress level is complementary to the application rate limit we built in Article 14.
15.09 Kubernetes: HorizontalPodAutoscaler
Ecommerce traffic rises and falls, so the number of pods must automatically adjust to the load. The HPA manifest below scales pods between 2 and 10 based on CPU and memory utilization, complete with stabilization policies.
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 if CPU > 70%
22 - type: Resource
23 resource:
24 name: memory
25 target:
26 type: Utilization
27 averageUtilization: 80 # scale up if memory > 80%
28 behavior:
29 scaleUp:
30 stabilizationWindowSeconds: 60 # wait 1 minute before scaling up again
31 policies:
32 - type: Pods
33 value: 2 # add max 2 pods at a time
34 periodSeconds: 60
35 scaleDown:
36 stabilizationWindowSeconds: 300 # wait 5 minutes before scaling downThe different stabilization windows for scale up (60 seconds) and scale down (300 seconds) prevent flapping — pods aren’t discarded too quickly when traffic briefly drops. The HPA only works if resource requests are set in the deployment, since utilization is computed relative to them.
15.10 Database Migration in Kubernetes
Database migrations must run before the new application version receives traffic. The Job manifest and Makefile snippet below run the migration as a separate Job, then roll out the deployment after the migration succeeds.
1# k8s/jobs/migration.yaml
2# Run BEFORE the deployment update
3
4apiVersion: batch/v1
5kind: Job
6metadata:
7 name: db-migration-${VERSION}
8 namespace: santekno-shop
9spec:
10 ttlSecondsAfterFinished: 3600 # delete the job after 1 hour
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-credentialsThe migration Job above runs once to prepare the database schema before release. The Makefile target below automates the sequence of building the image, running the migration, then rolling out the deployment.
1# Makefile target for deploy:
2deploy-staging:
3 # 1. Build and 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 (wait for completion)
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-shopRunning the migration as a Job with kubectl wait ensures the new deployment doesn’t start if the database schema fails to update. ttlSecondsAfterFinished automatically cleans up old Jobs so the cluster doesn’t accumulate Job objects.
15.11 GitHub Actions: CI/CD Pipeline for Staging
Manual deploys are error-prone, so the whole flow from test to smoke test must be automated. The GitHub Actions workflow below runs tests, builds the image, migrates, rolling-deploys, smoke-tests, and sends a Slack notification on every push to the develop branch.
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 the CI workflow from Article 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 # wait for pods to be 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 }}This pipeline applies layered gates: tests must pass before the build, the migration must succeed before the deploy, and the smoke test verifies that staging is actually serving requests. The registry caching layer makes subsequent image builds much faster.
15.12 Rollback Strategy
A problematic deploy must be reversible in seconds. The commands below show how to view history, roll back to the previous or a specific revision, and handle the database migration if it needs to be reverted.
1# Rollback the deployment if there's a problem
2
3# View revision history
4kubectl rollout history deployment/santekno-shop -n santekno-shop
5
6# Rollback to the previous version
7kubectl rollout undo deployment/santekno-shop -n santekno-shop
8
9# Rollback to a specific revision
10kubectl rollout undo deployment/santekno-shop \
11 --to-revision=3 -n santekno-shop
12
13# Verify the rollback
14kubectl rollout status deployment/santekno-shop -n santekno-shop
15
16# If a database migration was already applied:
17# Use the down migration
18migrate -path ./migrations -database "$DATABASE_URL" down 1A deployment rollback is instant because Kubernetes keeps the old revisions, but a database migration needs special care — a down migration is only safe if the change is reversible. Design migrations to be additive so an application rollback doesn’t require a schema rollback.
15.13 Resource Sizing
Deciding how many pods and how much resource you need should be based on estimation, not guessing. The calculation below derives Santekno Shop’s resource needs from a target of 100K MAU and 10K orders per day.
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 for 100K MAU
20
21Cache:
22 Redis: cache.t3.micro (1 vCPU, 0.5GB) → adequate
23
24Kafka:
25 3 brokers, 3 partitions per topic → adequate for 10K orders/day
26
27Load testing (Article 19 — Part 4):
28 k6 will validate these assumptionsThis estimate is an initial assumption that must be validated with a real load test in Article 19 — the conservative “1 pod ~50 RPS” number gives a safety margin. What matters: the sizing has a basis in calculation, not just bumping up replicas when there’s a problem.
15.14 Local Kubernetes with kind
Before touching the staging cluster, the manifests should be tested on a local Kubernetes. The commands below create a kind cluster with port mapping, load the local image, and apply the manifests for a quick verification.
1# Development Kubernetes cluster with kind (Kubernetes in Docker)
2brew install kind
3
4# Create a 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 the local Docker image into 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-shopWith kind, you can validate the entire set of manifests — deployment, service, probes — on a laptop without cloud costs. This catches YAML and configuration mistakes long before the pipeline touches staging.
15.15 Docker Image Size Optimization
Image size directly impacts pull speed and attack surface. The commands below show the result of the multi-stage build and how to verify the size, scan for vulnerabilities, and analyze layers.
1# Result of the multi-stage build:
2# Builder stage: ~1.5GB (golang:1.22-alpine with all deps)
3# Runtime stage: ~20MB (scratch + binary)
4# Difference: 98.7% smaller!
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:latestThe reduction from 1.5GB to around 21MB isn’t just a number — a small image means faster pulls, shorter cold starts, and fewer CVEs to patch. Make trivy part of the pipeline so vulnerabilities are caught before the image reaches production.
15.16 ConfigMap vs Secret: Guidelines
Wrongly placing credentials in a ConfigMap is a common security mistake. The guide below makes clear what belongs in a ConfigMap versus a Secret, along with best practices for managing secrets.
1ConfigMap:
2 PORT, ENV, LOG_LEVEL
3 KAFKA_BROKERS (not sensitive)
4 DB_MAX_OPEN_CONNS
5 Feature flags
6 Not: DATABASE_URL, passwords, API keys
7
8Secret:
9 DATABASE_URL (contains a password)
10 JWT_ACCESS_SECRET, JWT_REFRESH_SECRET
11 PAYMENT_WEBHOOK_SECRET
12 SMTP_PASSWORD
13 API keys for the payment gateway
14
15Best practices:
16 - Use the External Secrets Operator (ESO) + HashiCorp Vault or AWS SM
17 - Don't base64-encode secrets in Git (that's not encryption!)
18 - Rotate secrets periodically
19 - Audit access to secretsThe simple rule: anything that can be used to access another system is a Secret, everything else is a ConfigMap. Remember again that base64 is not encryption — for production, sync secrets from Vault or AWS Secrets Manager via ESO.
15.17 Staging Environment Checklist
A staging environment is considered “ready” only if all aspects of infrastructure, application, monitoring, and security are met. The checklist below summarizes everything that must be checked before a staging deploy is declared passing.
1Before a staging deploy is considered "ready":
2
3Infrastructure:
4□ PostgreSQL 15 with the pgvector extension
5□ Redis 7 with persistence
6□ Kafka cluster with 3 partitions per topic
7□ TLS certificate (Let's Encrypt via cert-manager)
8□ Ingress controller (nginx)
9
10Application:
11□ Health endpoint returns 200 (/health)
12□ Readiness endpoint returns 200 (/ready) — DB and Redis connected
13□ GET /api/v1/products returns products from seed data
14□ POST /api/v1/auth/register works
15□ POST /api/v1/auth/login works
16□ Swagger UI accessible (optional)
17
18Monitoring:
19□ Prometheus scraping /metrics
20□ Grafana dashboard exists
21□ Alert rules configured (Article 18 — Part 4)
22□ Log aggregation (Loki or CloudWatch)
23
24Security:
25□ Secrets not in Git
26□ Security headers present (curl -I https://api.staging.santekno.com)
27□ TLS 1.2+ only
28□ Non-root containerThis checklist forces thorough verification instead of relying on “it seems to be working.” Keep it as a template to be ticked off every time you set up or review a staging environment.
15.18 Database in Kubernetes
For staging, Postgres can run inside the cluster as a StatefulSet with a persistent volume. The manifest below shows that setup, while making clear that production should use a managed database.
1# For staging: PostgreSQL as a 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: use a managed database (RDS, Cloud SQL)
40# More reliable, automatic backups, automatic failoverA StatefulSet with volumeClaimTemplates gives Postgres a stable identity and persistent storage that isn’t lost when the pod restarts. For staging this is enough, but in production a managed database (RDS/Cloud SQL) is far more reliable because it handles backups and failover automatically.
15.19 Kustomize: Base and Overlay
Staging and production share many manifests but differ in a few values like replica count. The Kustomize structure below separates the shared base from the per-environment overlays.
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/ → Topic 10
16│ ├── kustomization.yaml → replicas: 4, prod ingress, resource limits
17│ └── patch-resources.yamlThe directory structure above separates the base manifests from the per-environment overlays. The staging kustomization file below shows how the overlay overrides the base with staging-specific replicas and ingress.
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-shopWith the base + overlay pattern, one change in the base automatically applies to all environments while the specific differences are managed via patches. This eliminates manifest duplication that’s prone to drift between staging and production.
15.20 Summary: Part 3 Complete
The Santekno Shop infrastructure is now ready from local development all the way to staging:
Dockerfile: multi-stage, FROM scratch, ~20MB binary, non-root user.
docker-compose: full development stack (app + postgres + redis + kafka + tools), hot reload with 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: a Kubernetes Job that runs before the deployment update.
Health probes: liveness (/health) and readiness (/ready) with the right timeouts.
With this, Part 3 is complete — all five infrastructure articles (database migrations, Kafka integration, Redis caching, API Gateway, Docker + Kubernetes) are done. Part 4 (Articles 16-20) will move into the Production Baseline: testing strategy, CI/CD with AI quality gates, observability, performance baseline, and the bridge to Topic 6. The first step of Part 4 is building a testing strategy that turns the spec into unit, integration, and E2E tests.