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

Vengala Vinay

Having 12+ Years of Experience in Software Development

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

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

Understanding the Blue-Green Deployment Pattern

Blue-Green deployment is a strategy that minimizes downtime and risk by running two identical production environments, referred to as “Blue” and “Green.” At any given time, only one environment is live, serving all production traffic. The other environment is idle, used for deployment and testing. Once the new version is deployed and validated on the idle environment, traffic is switched over. This allows for instant rollback by simply switching traffic back to the original environment if issues arise.

AWS Infrastructure for Blue-Green Deployments

For PHP applications on AWS, a robust Blue-Green setup typically involves several key services:

  • Elastic Load Balancing (ELB): Specifically, an Application Load Balancer (ALB) is crucial for routing traffic.
  • Elastic Compute Cloud (EC2) Instances: Two distinct sets of EC2 instances, one for the “Blue” environment and one for the “Green.”
  • Auto Scaling Groups (ASGs): To manage the EC2 instances within each environment, ensuring desired capacity and health.
  • Amazon S3: For storing deployment artifacts and potentially static assets.
  • AWS CodeDeploy: To automate the deployment process to the EC2 instances.
  • Amazon Route 53: For DNS management and the critical traffic switching mechanism.

Setting Up the Load Balancer and Target Groups

We’ll use an Application Load Balancer (ALB) to manage traffic. The core of the Blue-Green strategy here lies in manipulating the ALB’s target groups. We’ll have two target groups, one for the Blue environment and one for the Green. Initially, the ALB will point to the Blue target group.

First, create two Auto Scaling Groups:

  • ASG-Blue: Configured to launch EC2 instances for the Blue environment.
  • ASG-Green: Configured to launch EC2 instances for the Green environment.

Next, create two Target Groups in the EC2 console:

  • TG-Blue: Points to the instances managed by ASG-Blue.
  • TG-Green: Points to the instances managed by ASG-Green.

Configure health checks for both target groups. These health checks should point to a specific endpoint in your PHP application (e.g., /healthz) that returns a 200 OK status if the application is healthy.

Now, create an Application Load Balancer. When configuring listeners, set up a rule that forwards traffic to TG-Blue by default. We will later modify this rule to switch traffic to TG-Green.

Automating Deployments with AWS CodeDeploy

AWS CodeDeploy is instrumental in orchestrating the deployment to the EC2 instances. We’ll create a CodeDeploy Application and then a Deployment Group for each environment.

1. Create a CodeDeploy Application:

In the AWS CodeDeploy console, create a new application, for example, php-blue-green-app. Choose “EC2/On-Premises” as the compute platform.

2. Create Deployment Groups:

Create two deployment groups under this application:

  • DG-Blue: Associate this with ASG-Blue. Configure the load balancer to use TG-Blue.
  • DG-Green: Associate this with ASG-Green. Configure the load balancer to use TG-Green.

Crucially, for the “Deployment configuration,” select a strategy that supports Blue-Green deployments. AWS CodeDeploy offers a “Blue/Green deployment” option directly. When you select this, CodeDeploy will automatically handle the traffic shifting. You’ll need to specify the ALB listener and the target groups.

3. Create an appspec.yml file:

This file defines the lifecycle hooks for your deployment. Place this file in the root of your application’s source bundle.

version: 0.0
Resources:
  - TargetService:
      Type: AWS::EC2::Instance
      Properties:
        Duration: 60 minutes
        Image:
          Os: LINUX
        Files:
          - Source: /path/to/your/app/files
            Destination: /var/www/html
Hooks:
  BeforeInstall:
    - location: scripts/before_install.sh
  AfterInstall:
    - location: scripts/after_install.sh
  ApplicationStart:
    - location: scripts/application_start.sh
  ApplicationStop:
    - location: scripts/application_stop.sh
  ValidateService:
    - location: scripts/validate_service.sh

4. Deployment Scripts:

The scripts referenced in appspec.yml are critical. For a PHP application, these might include:

scripts/before_install.sh:

#!/bin/bash
# Stop any running PHP processes (e.g., FPM)
sudo systemctl stop php-fpm
# Remove old application files if necessary
sudo rm -rf /var/www/html/*

scripts/after_install.sh:

#!/bin/bash
# Copy new application files
sudo cp -R /opt/codedeploy-deployment-staging/files/* /var/www/html/
# Set correct permissions
sudo chown -R www-data:www-data /var/www/html/
sudo chmod -R 755 /var/www/html/
# Install Composer dependencies
cd /var/www/html/
composer install --no-dev --optimize-autoloader

scripts/application_start.sh:

#!/bin/bash
# Start PHP-FPM
sudo systemctl start php-fpm

scripts/validate_service.sh:

#!/bin/bash
# Wait for the application to become healthy
# This script is crucial for CodeDeploy's Blue/Green traffic shifting
# It should poll the health endpoint until it returns a 200 OK
HEALTH_CHECK_URL="http://localhost/healthz" # Or the internal IP of the instance
MAX_ATTEMPTS=30
SLEEP_INTERVAL=10

for ((i=1; i<=$MAX_ATTEMPTS; i++)); do
    if curl -s --head "$HEALTH_CHECK_URL" | grep "200 OK" > /dev/null; then
        echo "Application is healthy."
        exit 0
    fi
    echo "Waiting for application to become healthy. Attempt $i/$MAX_ATTEMPTS..."
    sleep $SLEEP_INTERVAL
done

echo "Application did not become healthy within the allowed time."
exit 1

Orchestrating the Traffic Switch with Route 53

While CodeDeploy can manage the traffic shift for ALB target groups, for more granular control or if you’re not using CodeDeploy’s native Blue-Green feature, you can leverage Amazon Route 53. This involves updating DNS records to point your domain to the Blue or Green environment.

However, the most common and integrated approach with ALB and CodeDeploy is to let CodeDeploy handle the traffic shifting. When CodeDeploy performs a Blue-Green deployment, it:

  • Launches new instances for the Green environment.
  • Deploys the new application version to these Green instances.
  • Runs the ValidateService hook to ensure the Green environment is healthy.
  • Once validated, it shifts traffic from the Blue target group to the Green target group on the ALB.
  • Terminates the old Blue instances (or keeps them as a rollback option).

If you are managing traffic manually via Route 53, you would typically have two different CNAME or A records pointing to the ALB, and you’d update the DNS record for your production domain to switch between them. This requires careful TTL management to ensure propagation.

The Deployment Workflow

Here’s a typical workflow for a zero-downtime Blue-Green deployment:

  1. Prepare New Version: Package your PHP application code, including the appspec.yml file and deployment scripts, into a ZIP archive.
  2. Upload to S3: Upload this archive to an S3 bucket.
  3. Initiate CodeDeploy: Trigger a new deployment in AWS CodeDeploy. Select the php-blue-green-app application and the DG-Green deployment group. Point CodeDeploy to the S3 artifact.
  4. CodeDeploy Execution:
    • CodeDeploy launches new EC2 instances for the Green environment (if not already running via ASG).
    • It copies the application files to the Green instances.
    • It executes the lifecycle hooks (BeforeInstall, AfterInstall, ApplicationStart).
    • It runs the ValidateService hook. This is the critical step where your application must signal its readiness.
  5. Traffic Shifting: If ValidateService succeeds, CodeDeploy automatically updates the ALB listener rules to shift traffic from the Blue target group to the Green target group.
  6. Termination of Old Environment: After a configurable waiting period, CodeDeploy terminates the old Blue instances.

Rollback Strategy

The beauty of Blue-Green is the instant rollback capability. If a deployment fails validation or if issues are detected post-deployment:

  • CodeDeploy Rollback: If CodeDeploy’s ValidateService hook fails, it will automatically roll back the deployment, shifting traffic back to the Blue environment and terminating the faulty Green instances.
  • Manual Rollback: If issues are discovered after traffic has been shifted to Green, you can initiate a rollback. This typically involves triggering a new deployment of the *previous stable version* to the *new* Blue environment (which was previously Green) and then switching traffic back. Alternatively, if you’re using Route 53 for traffic management, you’d simply update the DNS records to point back to the original Blue environment’s ALB. With CodeDeploy’s ALB integration, you can often trigger a “Rollback” action directly within the CodeDeploy console for a failed deployment, or initiate a new deployment of the last known good revision.

PHP Application Considerations

Ensure your PHP application is stateless or that any state can be managed externally (e.g., in a shared Redis cache or database). Session management is a common challenge. Using a shared session handler (like Redis or Memcached) accessible by both Blue and Green environments is essential. Also, ensure your application’s configuration is externalized and can be easily updated or managed per environment.

The healthz endpoint should be robust, checking not just if the web server is running, but if critical dependencies (database connections, cache services) are available.

<?php
// public/healthz.php
header('Content-Type: application/json');

// Basic health check: can we connect to the database?
$db_host = getenv('DB_HOST');
$db_name = getenv('DB_NAME');
$db_user = getenv('DB_USER');
$db_pass = getenv('DB_PASS');

try {
    new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    // Add checks for other critical services like Redis, etc.
    echo json_encode(['status' => 'ok', 'message' => 'Application is healthy.']);
    http_response_code(200);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed: ' . $e->getMessage()]);
    http_response_code(503); // Service Unavailable
}
?>

Conclusion

Implementing zero-downtime Blue-Green deployments on AWS for PHP applications requires careful orchestration of AWS services. By leveraging ALB, Auto Scaling Groups, CodeDeploy, and a well-defined deployment strategy with robust health checks, you can achieve seamless updates with minimal risk and zero downtime for your users.

Primary Sidebar

A little about the Author

Having 12+ Years of Experience in Software Development, Vinay is a principal software architect, senior systems engineer, and elite technical consultant. He specializes in bespoke PHP/WordPress development, high-performance Magento 2 & Shopify architectures, custom plugin/theme development from scratch, and legacy code modernization (including VB6, VB.NET, PyQt, and Crystal Reports). Known for solving complex database bottlenecks, speed optimization (Core Web Vitals), and advanced security code auditing, Vinay engineers production-ready systems designed to scale under heavy concurrent load conditions.



Chat on WhatsApp

Recent Posts

  • Step-by-Step Guide to building a custom database optimizer portal block for Gutenberg using Alpine.js lightweight states
  • How to securely integrate Slack Webhooks integration endpoints into WordPress custom plugins using Rewrite API custom endpoints
  • How to securely integrate GitHub API repositories endpoints into WordPress custom plugins using WordPress Database Class ($wpdb)
  • How to securely integrate HubSpot Contacts endpoints into WordPress custom plugins using Rewrite API custom endpoints
  • Troubleshooting namespace class loading collisions in production when using modern Sage Roots modern environments wrappers

Categories

  • apache (1)
  • Business & Monetization (390)
  • Centos (4)
  • Comparisons & Decision Making (55)
  • Debian (2)
  • Debugging & Troubleshooting (609)
  • Desktop Applications (14)
  • DevOps (7)
  • DevOps & Cloud Scaling (962)
  • Django (1)
  • Laravel (4)
  • Migration & Architecture (192)
  • Mobile Applications (24)
  • MySQL (1)
  • Performance & Optimization (824)
  • PHP (5)
  • PHP Development (30)
  • Plugins & Themes (244)
  • Programming Languages (9)
  • Python (20)
  • Ruby on Rails (1)
  • Security & Compliance (587)
  • SEO & Growth (492)
  • Server (23)
  • Ubuntu (9)
  • VB6 & VB.NET (8)
  • Web Applications & Frontend (19)
  • Web Assembly (Wasm) (2)
  • WordPress (22)
  • WordPress Plugin Development (136)
  • WordPress Theme Development (357)

Recent Posts

  • Step-by-Step Guide to building a custom database optimizer portal block for Gutenberg using Alpine.js lightweight states
  • How to securely integrate Slack Webhooks integration endpoints into WordPress custom plugins using Rewrite API custom endpoints
  • How to securely integrate GitHub API repositories endpoints into WordPress custom plugins using WordPress Database Class ($wpdb)

Top Categories

  • DevOps & Cloud Scaling (962)
  • Performance & Optimization (824)
  • Debugging & Troubleshooting (609)
  • Security & Compliance (587)
  • SEO & Growth (492)
  • Business & Monetization (390)

Our Products

  • ERP & LMS Systems (4)
  • Directories & Marketplaces (4)
  • Healthcare Portals (3)
  • Point of Sale (POS) (2)
  • E-Commerce Engines (2)

Our Services

  • E-Commerce Development (10)
  • WordPress Development (8)
  • Python & Desktop GUI (7)
  • General Consulting (7)
  • Legacy Modernization (5)
  • Mobile App Development (4)

Copyright © 2026 · Vinay Vengala