Prompt
How do I use Kubernetes for blue-green deployments?
Latest observation
Blue-green deployments in Kubernetes mean you run two nearly identical environments:
- Blue = current production version
- Green = new version you want to release
You switch traffic from Blue to Green only after the new version is verified. If something goes wrong, you switch back quickly.
Common Kubernetes approach
1) Deploy both versions
Create two Deployments, one for each version:
app-blueapp-green
Each has its own Pods, but both run the same app with different image tags/configs.
2) Use one Service to route traffic
Create a Kubernetes Service that points to only one version at a time by selecting labels:
- Initially, Service selects
version: blue - After validation, change Service selector to
version: green
This is the main traffic switch.
3) Validate green before switching
Before changing the Service:
- run smoke tests against green
- check logs/metrics
- verify readiness/liveness probes
4) Switch traffic
Update the Service selector:
spec:
selector:
app: myapp
version: green
Kubernetes will start sending new traffic to green Pods.
5) Roll back if needed
If green has issues, switch the Service selector back to blue.
Example
Blue Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-blue
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: blue
template:
metadata:
labels:
app: myapp
version: blue
spec:
containers:
- name: myapp
image: myapp:1.0.0
ports:
- containerPort: 8080
Green Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-green
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: green
template:
metadata:
labels:
app: myapp
version: green
spec:
containers:
- name: myapp
image: myapp:1.1.0
ports:
- containerPort: 8080
Service
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
version: blue
ports:
- port: 80
targetPort: 8080
Switching to green
Patch the Service:
kubectl patch service myapp-service -p '{"spec":{"selector":{"app":"myapp","version":"green"}}}'
Important considerations
Readiness probes
Make sure Pods only receive traffic when ready:
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
Sticky sessions/state
Blue-green works best for stateless apps. If your app has:
- in-memory session state
- local files
- incompatible database migrations
you need to handle those carefully.
Database migrations
Prefer backward-compatible migrations so both blue and green can work during the transition.
Resource usage
Blue-green temporarily doubles your resource usage since both versions run at once.
Alternatives
You can also use:
- Ingress/Load Balancer switching
- Argo Rollouts
- Flagger
- Service mesh like Istio for more advanced traffic splitting
These tools can make blue-green safer and more automated.
If you want, I can also give you:
- a full working YAML example,
- an Argo Rollouts blue-green setup, or
- a step-by-step rollout workflow.