🔧 DevOps

Blue-Green Deployment

Blue-Green Deployment

A zero-downtime deployment strategy that alternates between two identical production environments (blue/green). A new version is deployed to the inactive environment and traffic is then switched via a load balancer, enabling deployment without downtime and an immediate rollback if problems occur.

📖 Detailed Explanation

Blue-Green Deployment is a strategy of deploying while maintaining two identical production environments. The environment currently receiving traffic is called 'blue,' and the idle environment where the new version will be deployed is called 'green.' After the new version is deployed and testing is complete, traffic is switched to green via the load balancer or DNS.

This technique was popularized in the 2010 book "Continuous Delivery" by Jez Humble and David Farley. Companies operating large-scale services such as Netflix, Amazon, and Facebook adopted it for zero-downtime deployment, and advances in Kubernetes and cloud services have made it easier to implement.

The core principle is simple. While the blue environment is live, you deploy the new version to the green environment and test it thoroughly. Once all verification is complete, you change only the load balancer configuration to switch traffic to green. If a problem occurs, switching traffic back to blue provides an instant rollback. The switch takes only a few seconds.

In practice, blue-green deployment is essential for services where high availability matters. However, it requires twice the infrastructure cost, and database schema changes need additional consideration. It is also widely used in AI model serving, where the common pattern is to deploy a new model version to the green environment and switch after A/B testing.

┌─────────────────────────────────────────────────────────┐
│                    Load Balancer                        │
│                         │                               │
│            ┌────────────┴────────────┐                  │
│            ▼                         ▼                  │
│    ┌──────────────┐          ┌──────────────┐          │
│    │  🔵 BLUE     │          │  🟢 GREEN    │          │
│    │  (v1.0)      │  ──────▶ │  (v2.0)      │          │
│    │  [ACTIVE]    │  Switch  │  [STANDBY]   │          │
│    └──────────────┘          └──────────────┘          │
│                                                         │
│    배포 후 트래픽 전환: Blue → Green                    │
│    롤백 필요시: Green → Blue (수 초 내 완료)            │
└─────────────────────────────────────────────────────────┘
                    

📊 Deployment Strategy Comparison

Strategy Downtime Rollback Speed Infrastructure Cost Suitable Situations
Blue-Green None Instant (seconds) 2x Mission-critical services
Canary None Fast (minutes) 1.1-1.5x When gradual validation is needed
Rolling None Slow (minutes to hours) 1x Cost-sensitive environments
Regenerate Yes Slow 1x Development/staging environments

💻 Code Example

An example of implementing blue-green deployment on Kubernetes and AWS.

# blue-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-blue
  labels:
    app: myapp
    version: 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
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
---
# green-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-green
  labels:
    app: myapp
    version: green
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
      version: green
  template:
    metadata:
      labels:
        app: myapp
        version: green
    spec:
      containers:
      - name: myapp
        image: myapp:2.0.0  # 새 버전
        ports:
        - containerPort: 8080
---
# service.yaml (블루로 트래픽 라우팅)
apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  selector:
    app: myapp
    version: blue  # 이 값을 green으로 변경하면 전환!
  ports:
  - port: 80
    targetPort: 8080

# 전환 명령어
# kubectl patch service myapp-service -p '{"spec":{"selector":{"version":"green"}}}'

# 롤백 명령어
# kubectl patch service myapp-service -p '{"spec":{"selector":{"version":"blue"}}}'
# appspec.yml (AWS CodeDeploy Blue-Green)
version: 0.0
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: "arn:aws:ecs:region:account:task-definition/myapp:2"
        LoadBalancerInfo:
          ContainerName: "myapp"
          ContainerPort: 8080
        PlatformVersion: "LATEST"

Hooks:
  - BeforeInstall: "LambdaFunctionToValidateBeforeInstall"
  - AfterInstall: "LambdaFunctionToValidateAfterInstall"
  - AfterAllowTestTraffic: "LambdaFunctionToRunTests"
  - BeforeAllowTraffic: "LambdaFunctionToValidateBeforeTraffic"
  - AfterAllowTraffic: "LambdaFunctionToValidateAfterTraffic"

# deployment-config.json
{
  "deploymentConfigName": "CodeDeployDefault.ECSLinear10PercentEvery1Minutes",
  "computePlatform": "ECS",
  "trafficRoutingConfig": {
    "type": "TimeBasedLinear",
    "timeBasedLinear": {
      "linearInterval": 1,
      "linearPercentage": 10
    }
  }
}

# AWS CLI 배포 명령
# aws deploy create-deployment \
#   --application-name MyApp \
#   --deployment-group-name MyDeploymentGroup \
#   --revision revisionType=S3,bucket=mybucket,key=myapp.zip
#!/bin/bash
# blue-green-switch.sh - Nginx 블루-그린 전환 스크립트

NGINX_CONF="/etc/nginx/conf.d/upstream.conf"
BLUE_PORT=8080
GREEN_PORT=8081
CURRENT=$(grep "server 127.0.0.1:" $NGINX_CONF | grep -oP '\d+')

echo "현재 활성 환경: Port $CURRENT"

if [ "$CURRENT" == "$BLUE_PORT" ]; then
    NEW_PORT=$GREEN_PORT
    NEW_ENV="GREEN"
else
    NEW_PORT=$BLUE_PORT
    NEW_ENV="BLUE"
fi

# 새 환경 헬스체크
echo "헬스체크: $NEW_ENV (Port $NEW_PORT)..."
if ! curl -sf http://127.0.0.1:$NEW_PORT/health > /dev/null; then
    echo "❌ 헬스체크 실패! 전환 중단"
    exit 1
fi
echo "✅ 헬스체크 통과"

# Nginx 설정 업데이트
echo "트래픽 전환: $CURRENT → $NEW_PORT"
sed -i "s/server 127.0.0.1:$CURRENT/server 127.0.0.1:$NEW_PORT/" $NGINX_CONF

# Nginx 리로드 (무중단)
nginx -t && nginx -s reload

echo "✅ 전환 완료! 현재 활성: $NEW_ENV (Port $NEW_PORT)"

# 롤백 스크립트 생성
cat > /tmp/rollback.sh << EOF
sed -i "s/server 127.0.0.1:$NEW_PORT/server 127.0.0.1:$CURRENT/" $NGINX_CONF
nginx -t && nginx -s reload
echo "롤백 완료: Port $CURRENT"
EOF
chmod +x /tmp/rollback.sh
echo "롤백 명령: /tmp/rollback.sh"

🗣️ Examples of Practical Conversations

💬 In a Deployment Meeting

"Today's v2.0 deployment will be done blue-green. Blue is currently live; once the new version is deployed to green and QA is complete, we'll switch at 5 PM. Please designate a rollback owner just in case. The switch takes just one kubectl patch line."

💬 During Incident Response

"We found a memory leak in the green environment. I'll roll back to blue right now. We only need to change the service selector, so we'll recover within 10 seconds. Once the rollback is done, I'll analyze the cause in the green environment."

💬 In an Architecture Review

"The downside of blue-green is that infrastructure cost doubles, and with high GPU instance costs like our AI inference servers, that's a burden. Shifting traffic 10% at a time with a canary deployment may be more cost-efficient."

⚠️ Cautions

❌
Caution with database schema changes

When blue and green share the same DB, schema changes must be compatible with both versions. Only drop a column after neither version uses it.

❌
Missing session state management

If you use in-memory sessions, user sessions are lost at the switch. Use a Redis or DB-based session store, or apply stateless authentication such as JWT.

✅
The right approach

Perform sufficient testing (smoke tests, load tests) in the green environment before switching. Implement health check endpoints, and strengthen monitoring even after the switch so you can roll back quickly if problems occur.

🔥 Real-World Incidents

Knight Capital 2012

$440 million lost in 45 minutes - deployment failure

Cause: The new code was not deployed to 1 of 8 servers, leaving old and new versions mixed

Impact: A large volume of erroneous orders, $440 million lost in 45 minutes, company bankruptcy

Lesson: Blue-green deployment ensures consistency across the whole environment; automated deployment verification is essential

📎 Detailed Analysis
GitLab 2017

Database deletion incident - rollback impossible

Cause: rm -rf was accidentally run on the production DB, and backups were not working

Impact: 6 hours of data lost, 18 hours of service outage

Lesson: Blue-green is effective for application rollbacks, but DB failures require a separate backup strategy

📎 GitLab Official Postmortem

📝 Comprehension Quiz

Q1. What is the biggest advantage of blue-green deployment?

Q2. What is the correct approach to database schema changes in blue-green deployment?

Q3. What characterizes blue-green compared to canary deployment?

🔗 Related Terms

📚 Learn More