• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar
  • Home
  • Projects
  • Products
  • Themes
  • Tools
  • Request for Quote

Vengala Vinay

Having 9+ Years of Experience in Software Development

  • Home
  • WordPress
  • PHP
    • Codeigniter
  • Django
  • Magento
  • Selenium
  • Server
Home » Zero-Downtime Blue-Green Deployment Pipelines for WooCommerce Applications on AWS

Zero-Downtime Blue-Green Deployment Pipelines for WooCommerce Applications on AWS

Architectural Overview: Blue-Green for WooCommerce

Implementing zero-downtime deployments for a WooCommerce application on AWS necessitates a robust strategy that isolates production traffic from the deployment environment. The Blue-Green deployment model is ideal for this. We’ll maintain two identical production environments: “Blue” (current production) and “Green” (new version). Traffic is initially directed to Blue. Once Green is fully deployed and validated, traffic is switched from Blue to Green. This allows for instant rollback by simply switching traffic back to Blue if issues arise in Green.

AWS Infrastructure Components

Our setup will leverage several AWS services:

  • Elastic Load Balancing (ELB): Specifically, an Application Load Balancer (ALB) to distribute traffic and manage listener rules for traffic shifting.
  • Auto Scaling Groups (ASGs): To manage the instances for both Blue and Green environments, ensuring scalability and self-healing.
  • EC2 Instances: Hosting the WooCommerce application, web server (e.g., Nginx/Apache), and PHP-FPM.
  • Amazon RDS: For the MySQL database. Crucially, the database schema must be backward compatible to avoid issues during the transition.
  • Amazon S3: For storing static assets (media uploads, themes, plugins) which are shared between Blue and Green environments.
  • AWS Systems Manager (SSM): For automated deployment tasks and configuration management.
  • AWS CodeDeploy (Optional but Recommended): For orchestrating the deployment process to EC2 instances.

Database Strategy: Backward Compatibility is Key

The most critical aspect of a zero-downtime deployment is the database. WooCommerce applications often have complex database schemas. For Blue-Green to work seamlessly, all database schema changes in the “Green” deployment must be backward compatible with the “Blue” application. This means:

  • New columns should have default values or be nullable.
  • Dropping columns or tables is strictly forbidden until the “Blue” environment is decommissioned.
  • Any data migrations that alter existing data must be carefully planned and executed in a way that doesn’t break the older version of the application.

A common pattern is to deploy schema changes as a separate step before deploying the new application code. This allows the “Blue” environment to adapt to the new schema without breaking. Then, the “Green” application, which expects the new schema, can be deployed. If a rollback is needed, the “Blue” application (still running) must be able to function with the new schema. This implies that schema changes should ideally be additive or reversible.

Setting Up the Environments

We’ll use two distinct Auto Scaling Groups, each associated with the same ALB. The ALB will initially direct all traffic to the “Blue” ASG. The “Green” ASG will be configured to have a desired capacity of 0 instances, or be in a “standby” state, until a deployment is initiated.

ALB Listener Rules

The ALB will have a default listener that forwards traffic to the “Blue” target group. We’ll use a listener rule to conditionally forward traffic. Initially, this rule will point to the “Blue” target group. During a deployment, we’ll modify this rule.

Target Groups

We need two target groups, one for “Blue” and one for “Green”. Both target groups will point to the same VPC and subnet configuration, but will be associated with their respective ASGs.

Auto Scaling Groups Configuration

Each ASG will use the same Launch Template, ensuring identical instance configurations. The key difference will be the ASG’s association with its respective target group.

Deployment Workflow with AWS CodeDeploy

AWS CodeDeploy simplifies the process of deploying applications to EC2 instances. We’ll configure CodeDeploy to manage deployments to our “Green” environment.

CodeDeploy Application and Deployment Group

Create a CodeDeploy application (e.g., `woocommerce-app`). Within this application, create a deployment group for the “Green” environment. This deployment group will target the EC2 instances within the “Green” ASG. Ensure the service role for CodeDeploy has necessary permissions to interact with EC2, ASG, and ALB.

`appspec.yml` for CodeDeploy

The `appspec.yml` file defines the lifecycle hooks for CodeDeploy. This is where we’ll orchestrate the deployment steps.

version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/html/woocommerce
hooks:
  BeforeInstall:
    - location: scripts/before_install.sh
      timeout: 300
      runas: root
  AfterInstall:
    - location: scripts/after_install.sh
      timeout: 600
      runas: root
  ApplicationStart:
    - location: scripts/application_start.sh
      timeout: 300
      runas: root
  ValidateService:
    - location: scripts/validate_service.sh
      timeout: 300
      runas: root

Deployment Scripts

These scripts will be part of your application’s repository and will be executed by CodeDeploy.

`scripts/before_install.sh`

#!/bin/bash
# Stop web server to prevent serving stale content during deployment
systemctl stop nginx
systemctl stop php-fpm

# Remove old application files (optional, depending on deployment strategy)
# rm -rf /var/www/html/woocommerce/*

# Ensure correct ownership and permissions
chown -R www-data:www-data /var/www/html/woocommerce
chmod -R 755 /var/www/html/woocommerce

`scripts/after_install.sh`

#!/bin/bash
# Navigate to the application directory
cd /var/www/html/woocommerce

# Install Composer dependencies
composer install --no-dev --optimize-autoloader

# Clear WooCommerce and theme/plugin caches
wp cache flush
wp rewrite flush --hard
# If using a specific caching plugin, add its flush command here
# e.g., wp redis flush (for WP Redis)

# Run database migrations (if any, ensure backward compatibility)
# php artisan migrate --force # Example for Laravel-based apps, adapt for WooCommerce

# Ensure correct ownership and permissions after composer install
chown -R www-data:www-data /var/www/html/woocommerce
chmod -R 755 /var/www/html/woocommerce

`scripts/application_start.sh`

#!/bin/bash
# Start web server and PHP-FPM
systemctl start php-fpm
systemctl start nginx

`scripts/validate_service.sh`

#!/bin/bash
# This script is crucial for CodeDeploy's validation.
# It should perform checks to ensure the application is healthy and serving correctly.

# Wait for the web server to respond
sleep 10

# Perform a health check request to the application
# Replace with your actual health check endpoint or a critical page URL
HEALTH_CHECK_URL="http://localhost/wp-admin/admin-ajax.php?action=health_check" # Example

# Use curl to check the response. A 200 OK status code is generally good.
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" $HEALTH_CHECK_URL)

if [ "$HTTP_STATUS" -eq 200 ]; then
  echo "Application health check passed."
  exit 0
else
  echo "Application health check failed with status code: $HTTP_STATUS"
  exit 1
fi

The Zero-Downtime Deployment Process

This process assumes you have a CI/CD pipeline (e.g., Jenkins, GitLab CI, AWS CodePipeline) that triggers CodeDeploy.

Step 1: Prepare the “Green” Environment

If the “Green” ASG has a desired capacity of 0, scale it up to at least 1 instance. CodeDeploy will then provision instances based on the ASG’s desired count and launch template.

Step 2: Deploy to “Green” using CodeDeploy

Initiate a CodeDeploy deployment to the “Green” deployment group. CodeDeploy will pull the application code and execute the lifecycle hooks defined in `appspec.yml` on the instances in the “Green” ASG.

Step 3: Validate “Green” Environment

CodeDeploy’s `ValidateService` hook will run. If it passes, CodeDeploy marks the deployment as successful. However, this is an automated check. Manual validation is still recommended.

Step 4: Manual Validation (Crucial)

Before shifting traffic, perform thorough manual testing on the “Green” environment. This can be done by:

  • Temporarily updating DNS to point to the “Green” ALB’s CNAME (if using separate ALBs for Blue/Green, which is more complex).
  • Using a tool like `curl` with specific headers to force traffic to a specific instance in the “Green” ASG (requires direct instance access or advanced ALB rules).
  • The most common and safest method: using ALB listener rules to route a small percentage of traffic to the “Green” target group.

For the latter, you’d add a listener rule to your ALB:

Rule priority: 1
Condition: Host is example.com
Action: Forward to Target Group: green-target-group
Weight: 100%

Then, you can gradually increase the weight or use weighted target groups. A more direct approach for immediate validation is to modify the default rule.

Step 5: Traffic Shifting (The “Cutover”)

Once confident in the “Green” environment, shift all traffic. This is achieved by modifying the ALB listener rules. The simplest way is to change the default rule to point to the “Green” target group and remove/disable the rule pointing to “Blue”.

Using AWS CLI for Traffic Shifting

# Get the current default listener ARN
LISTENER_ARN=$(aws elbv2 describe-listeners --load-balancer-arn YOUR_ALB_ARN --query 'Listeners[0].ListenerArn' --output text)

# Get the ARN for the Green target group
GREEN_TG_ARN=$(aws elbv2 describe-target-groups --load-balancer-arn YOUR_ALB_ARN --query 'TargetGroups[?TargetGroupName==`green-target-group`].TargetGroupArn' --output text)

# Get the ARN for the Blue target group (to remove it from rules)
BLUE_TG_ARN=$(aws elbv2 describe-target-groups --load-balancer-arn YOUR_ALB_ARN --query 'TargetGroups[?TargetGroupName==`blue-target-group`].TargetGroupArn' --output text)

# Find the existing rule pointing to Blue (assuming it's the default rule or has a specific priority)
# This part can be tricky. It's often easier to delete and recreate the default rule.
# For simplicity, let's assume we're modifying the default rule's action.

# Get the default rule ARN
DEFAULT_RULE_ARN=$(aws elbv2 describe-rules --listener-arn $LISTENER_ARN --query 'Rules[?Priority==`default`].RuleArn' --output text)

# Modify the default rule to point to the Green target group
aws elbv2 modify-rule \
    --rule-arn $DEFAULT_RULE_ARN \
    --actions Type=forward,TargetGroupArn=$GREEN_TG_ARN

echo "Traffic shifted to Green environment."

# Optional: Remove the Blue target group from any other rules if necessary
# This might involve deleting specific rules or modifying them.
# For a clean cutover, ensure no traffic is still directed to Blue.

Step 6: Monitor “Green” Environment

Closely monitor application logs, error rates (CloudWatch Metrics), and user feedback after the traffic shift. If any critical issues are detected, proceed to rollback.

Step 7: Rollback (If Necessary)

If issues arise, immediately shift traffic back to the “Blue” environment by reversing the ALB listener rule modification. The “Blue” environment, still running and untouched, will resume serving traffic.

# Get the current default listener ARN
LISTENER_ARN=$(aws elbv2 describe-listeners --load-balancer-arn YOUR_ALB_ARN --query 'Listeners[0].ListenerArn' --output text)

# Get the ARN for the Blue target group
BLUE_TG_ARN=$(aws elbv2 describe-target-groups --load-balancer-arn YOUR_ALB_ARN --query 'TargetGroups[?TargetGroupName==`blue-target-group`].TargetGroupArn' --output text)

# Get the default rule ARN
DEFAULT_RULE_ARN=$(aws elbv2 describe-rules --listener-arn $LISTENER_ARN --query 'Rules[?Priority==`default`].RuleArn' --output text)

# Modify the default rule to point back to the Blue target group
aws elbv2 modify-rule \
    --rule-arn $DEFAULT_RULE_ARN \
    --actions Type=forward,TargetGroupArn=$BLUE_TG_ARN

echo "Traffic rolled back to Blue environment."

Step 8: Decommission “Blue” Environment

Once the “Green” environment has been stable for a sufficient period (e.g., 24-48 hours), you can safely decommission the “Blue” environment. This involves terminating the EC2 instances in the “Blue” ASG and potentially removing the “Blue” target group and ASG configuration.

Handling WooCommerce Specifics

Media Uploads and Static Assets

WooCommerce relies heavily on media uploads. Ensure that your media is stored in a centralized location accessible by both Blue and Green environments. Amazon S3 with CloudFront is the standard and recommended approach. Your application configuration should point to the S3 bucket for uploads and media serving. This eliminates the need to sync media files between environments.

Caching Layers

Aggressive caching is common in WooCommerce. Ensure your deployment scripts clear all relevant caches (WordPress object cache, page cache, CDN cache if applicable) after deployment and before traffic shifting. This includes:

  • Object Cache (e.g., Redis, Memcached): `wp cache flush`
  • Page Cache (e.g., W3 Total Cache, WP Super Cache): Requires specific plugin commands or manual clearing.
  • Opcode Cache (e.g., OPcache): Usually handled by restarting PHP-FPM.

Plugin and Theme Updates

Updates to plugins and themes should be treated as application code deployments. Ensure they are tested thoroughly in a staging environment before being included in a Blue-Green deployment. If a plugin update requires database schema changes, follow the backward compatibility guidelines mentioned earlier.

Advanced Considerations

Canary Deployments

For even greater safety, instead of a full traffic shift, implement a canary release. This involves routing a small percentage of traffic (e.g., 1-5%) to the “Green” environment first. Monitor this subset of users closely. If all metrics are good, gradually increase the percentage until 100% of traffic is on “Green”. This can be managed via ALB weighted target groups.

Automated Testing

Integrate automated end-to-end tests (e.g., using Cypress, Selenium) into your CI/CD pipeline. These tests should run against the “Green” environment *before* traffic shifting. A failed test suite should automatically halt the deployment process.

Infrastructure as Code (IaC)

Manage your AWS infrastructure using tools like Terraform or AWS CloudFormation. This ensures that your Blue and Green environments are consistently provisioned and can be easily recreated or modified.

Database Schema Migration Tools

For complex database changes, consider using dedicated schema migration tools that support zero-downtime strategies, such as:

  • pt-online-schema-change (from Percona Toolkit): Performs schema changes with minimal locking.
  • gh-ost (from GitHub): Another excellent tool for online schema migrations.

These tools can be integrated into your deployment pipeline to handle schema changes safely before application code deployment.

Primary Sidebar

A little about the Author

Having 9+ Years of Experience in Software Development.
Expertised in Php Development, WordPress Custom Theme Development (From scratch using underscores or Genesis Framework or using any blank theme or Premium Theme), Custom Plugin Development. Hands on Experience on 3rd Party Php Extension like Chilkat, nSoftware.

Recent Posts

  • Step-by-Step: Diagnosing thread pools deadlock during concurrent ActiveRecord transaction processing on Linode Servers
  • Securing Your E-commerce APIs: Preventing SQL Injection (SQLi) in customized checkout queries in WooCommerce Implementations
  • Disaster Recovery 101: Architecting Auto-Failovers for MySQL and Ruby Deployments on Linode
  • High-Throughput Caching Strategies: Scaling MySQL for Perl Application APIs
  • Disaster Recovery 101: Architecting Auto-Failovers for DynamoDB and Laravel Deployments on DigitalOcean

Copyright © 2026 · Vinay Vengala