How to Use Deployment Strategy in Kubernetes
In Kubernetes, you use the
strategy field in a Deployment to control how updates are applied to your pods. The two main strategies are RollingUpdate for gradual updates and Recreate for replacing all pods at once.Syntax
The strategy field in a Kubernetes Deployment defines how pods are updated during a deployment. It has two main types:
- RollingUpdate: Updates pods gradually to avoid downtime.
- Recreate: Deletes all old pods before creating new ones.
For RollingUpdate, you can specify maxUnavailable and maxSurge to control how many pods are updated at once.
yaml
strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1
Example
This example shows a Deployment using the RollingUpdate strategy. It updates pods one at a time, ensuring at least some pods are always running.
yaml
apiVersion: apps/v1 kind: Deployment metadata: name: example-deployment spec: replicas: 3 selector: matchLabels: app: example strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 template: metadata: labels: app: example spec: containers: - name: example-container image: nginx:1.21.0
Output
deployment.apps/example-deployment created
Common Pitfalls
Common mistakes when using deployment strategies include:
- Setting
maxUnavailableormaxSurgetoo high, causing downtime or resource overload. - Using
Recreatestrategy without understanding it causes downtime by deleting all pods before starting new ones. - Not specifying a strategy, which defaults to
RollingUpdatebut may not fit all use cases.
yaml
# Wrong way (causes downtime): strategy: type: Recreate # Right way (rolling update with controlled pods): strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1
Quick Reference
| Strategy | Description | Use Case |
|---|---|---|
| RollingUpdate | Updates pods gradually without downtime | Most common for production updates |
| Recreate | Deletes all pods before creating new ones | Simple apps where downtime is acceptable |
Key Takeaways
Use the strategy field in Deployment to control pod update behavior.
RollingUpdate is best for zero-downtime updates with controlled pod replacement.
Recreate strategy causes downtime by deleting all pods before new ones start.
Configure maxUnavailable and maxSurge to balance availability and speed.
Always test deployment strategy settings in a staging environment first.