Blue-Green Deployment on AWS Elastic Beanstalk Guide | Quantum Bits
Insight
How to Implement Blue-Green Deployment in AWS Elastic Beanstalk for Safer Application Releases
Anup GiriNovember 16, 2026
How to Implement Blue-Green Deployment in AWS Elastic Beanstalk for Safer Application Releases
Qbits
How to Implement Blue-Green Deployment in AWS Elastic Beanstalk for Safer Application Releases
It's a Tuesday afternoon, and your team has a release ready. The existing version is serving real customers, and the new one fixes a billing bug and adds a feature the sales team has been promising. You can update the live environment in place and hope nothing goes wrong, or you can find a way to prove the new version works before a single customer touches it.
Updating a running application directly carries real risks: capacity dips or brief outages while instances restart, bugs that only show up under production conditions, partially completed deployments that leave environments in mixed states, and rollbacks that mean redeploying under pressure.
Blue-Green Deployment in AWS Elastic Beanstalk addresses these risks by separating preparing a release from exposing it. You build and test the new version in a second environment, then redirect production traffic to it once you're confident. If something goes wrong, the previous environment is still there to go back to.
This tutorial walks through the full process with a Flask application: creating the Blue and Green environments, deploying and validating a new version, swapping production traffic, monitoring, rolling back, automating the workflow with CI/CD, and the production concerns (especially databases) that a simple URL swap doesn't solve.
What Is Blue-Green Deployment?
Blue-Green is a release strategy built on two parallel environments:
Blue is the current production environment. It serves live users and keeps running untouched while you prepare the next release.
Green is a separate environment running the new version. You deploy to it, test it, and verify it, all without affecting users.
When Green passes validation, production traffic moves from Blue to Green. Blue stays available as a rollback target until you're satisfied with the release.
flowchart TB
Users([Users]) --> DNS[Production URL / custom domain]
DNS -->|before swap| Blue
DNS -.->|after swap| Green
subgraph EB[AWS Elastic Beanstalk application]
Blue["Blue environment<br/>current version"]
Green["Green environment<br/>new version, validated"]
end
Blue --- DB[(Shared database<br/>outside the environments)]
Green --- DB
Green -. swap environment URLs .-> DNS
DNS -. rollback: swap back .-> Blue
The diagram shows the key idea: users reach the application through a stable production URL, and the swap changes which environment that URL points to. Both environments typically talk to the same externally managed database, which becomes important later.
About the author
Anup Giri
Building scalable software systems and AI-driven solutions for modern businesses.
Product strategyCloud architectureDevOps deliverySoftware support
Send us a message
Fill out the form below and we'll get back to you soon.
Why Use Blue-Green Deployment in AWS Elastic Beanstalk?
AWS Elastic Beanstalk manages the infrastructure behind a web application: EC2 instances, load balancing, Auto Scaling, and health monitoring. Several of its features map neatly to Blue-Green:
Managed environments. Each environment is a self-contained stack you can create, clone, and terminate.
Environment cloning. Copying an existing environment's configuration helps keep Green consistent with Blue.
Application version management. Every uploaded bundle is stored as a labeled version you can deploy to any environment.
Health monitoring. Environment health and events show whether a deployment succeeded.
Swap Environment URLs. Elastic Beanstalk exchanges the CNAME records of two environments, redirecting traffic to the new version.
The AWS documentation notes that an in-place update can leave your application briefly unavailable and recommends a Blue-Green deployment to avoid that. It also notes Blue-Green is required when you move to an incompatible platform version.
Limitations worth knowing:
It's a DNS-level swap, not weighted traffic shifting. The swap is not gradual. For a percentage-based canary, Elastic Beanstalk offers a separate traffic splitting deployment policy (covered below), or you can build weighted routing with Route 53.
DNS caching. Clients and resolvers may cache the old record, so some users may keep reaching the old environment for a while. AWS advises not terminating the old environment until the DNS change has fully propagated.
Not a guarantee of zero downtime. The approach minimizes risk, but outcomes depend on your application, connections, and network behavior.
Doubled infrastructure during the release window, which has a cost.
Databases need to live outside the environment. AWS states that Blue-Green requires your environment to run independently of your production database.
Prerequisites
Before you start, you'll need:
An active AWS account.
IAM permissions for Elastic Beanstalk and related services (EC2, Auto Scaling, Elastic Load Balancing, S3, CloudWatch, and IAM pass-role for the roles below).
An Elastic Beanstalk service role and an EC2 instance profile. The console can create them for you; they typically use AWS managed policies such as AWSElasticBeanstalkWebTier for the instance profile. Check the documentation for the current recommended policies.
A supported Python platform (this tutorial uses a current Python platform branch on Amazon Linux 2023).
The application source code and a requirements.txt.
Access to the Elastic Beanstalk Console, the AWS CLI, or the EB CLI.
An externally managed database (for example, Amazon RDS) if your app uses one.
Basic familiarity with deploying web applications.
The same process applies to other Elastic Beanstalk platforms such as Node.js, Java, and .NET; only the packaging and entry point differ.
Step-by-Step Implementation
Console labels change from time to time, so treat screenshot placeholders as markers for you to capture current screens.
Step 1: Create the Blue production environment
Sign in to the AWS Management Console and open Elastic Beanstalk.
Under platform, choose Python and a current platform branch.
Set the environment name to qbits-blue-production. Optionally set a domain prefix such as qbits-prod, which gives the environment a predictable URL.
For application code, choose Sample application for now, or upload your first version.
In Configure service access, choose the service role and EC2 instance profile (create them if needed).
Review the settings and launch.
📷 Screenshot placeholder: Create environment page showing the environment name and domain prefix.
Verify: When the environment health shows OK (green) and its URL returns your app, Blue is running. With the EB CLI, eb status qbits-blue-production shows the same information.
Tip: Point your custom domain (via a Route 53 alias or CNAME) at the Elastic Beanstalk URL that will represent production. Because the swap exchanges URLs between environments, your public domain stays unchanged.
Step 2: Clone Blue to create Green
Select qbits-blue-production.
Choose Actions → Clone environment.
Name it qbits-green-staging and set a different domain prefix, for example qbits-staging.
Review the configuration (platform version, instance type, scaling, environment variables).
Launch the clone.
Cloning copies the environment's configuration, which helps keep Green and Blue identical apart from the application version. Two caveats from the EB CLI documentation: a clone is created with the most recent platform version by default unless you choose otherwise, and cloned environments don't carry over security group ingress rules, so re-establish them and review anything else that may not have been copied. Verifying these details early prevents "it worked in staging" surprises.
Elastic Beanstalk's Python platform looks for a WSGI callable named application in application.py. Naming the Flask object app is a common reason for failed first deployments.
Verify: In Events, look for a successful deployment message. Environment health should return to OK. Opening the Green URL should show version 2.0.0, while the Blue URL still shows 1.0.0.
Step 5: Validate Green before release
This is the step that makes Blue-Green worth the effort. Test Green against production-like conditions before it receives real traffic:
Functional testing: exercise key user journeys.
API validation: call critical endpoints and check responses and status codes.
Health checks: confirm /health returns success and that Elastic Beanstalk health is OK.
Database connectivity: verify the app can read and write using production-like configuration, ideally against a safe or staging database.
Error logs: request logs from the environment and look for stack traces or warnings.
Performance: run a load or latency check against the Green URL.
Security: confirm HTTPS, security groups, and secrets handling match production.
A health endpoint that checks a dependency is more useful than one that always returns 200. Here is an illustrative version:
import os
import psycopg2 # add to requirements.txt if you use PostgreSQL
@application.route("/health")
def health():
try:
conn = psycopg2.connect(os.environ["DATABASE_URL"], connect_timeout=3)
with conn.cursor() as cur:
cur.execute("SELECT 1")
conn.close()
except Exception:
return jsonify(status="degraded"), 503
return jsonify(status="ok", version=APP_VERSION), 200
Keep health checks lightweight so they don't become a load source themselves, and never return secrets in the response.
Use Amazon CloudWatch alongside Elastic Beanstalk's own health view: environment health and instance metrics, application and web server logs, and alarms on error rates and latency. A simple smoke test from the command line:
Open the Elastic Beanstalk console and select the Blue environment (qbits-blue-production).
Choose Actions → Swap environment URLs.
In the Environment name field, select the Green environment (qbits-green-staging).
Confirm by choosing Swap.
Equivalent CLI commands:
aws elasticbeanstalk swap-environment-cnames \
--source-environment-name qbits-blue-production \
--destination-environment-name qbits-green-staging
# or with the EB CLI
eb swap qbits-blue-production --destination_name qbits-green-staging
Elastic Beanstalk exchanges the CNAME records of the two environments. The production URL now resolves to the environment running version 2.0.0, and the old production environment holds the staging URL. Note that environment names don't change, only the URLs, so qbits-green-staging is now the environment serving production. Many teams rename or tag environments by role to avoid confusion.
Verify: Request the production URL and confirm it returns version 2.0.0.
⚠️ This is a URL swap, not gradual traffic shifting. All new requests resolve to the new environment after DNS updates, subject to caching. If you want a percentage-based rollout, use the traffic splitting deployment policy or weighted routing in Route 53 instead. And as noted above, this approach reduces downtime risk but does not guarantee zero downtime in every scenario.
Step 7: Monitor the new production environment
Don't treat the swap as the finish line. For the first minutes and hours:
Check Elastic Beanstalk health and recent events.
Watch CloudWatch metrics: request counts, 4xx and 5xx rates, latency, CPU, and instance health.
Review application logs for new exceptions.
Confirm database connections and query behavior.
Walk through a few critical workflows manually (sign-in, checkout, key API calls).
Compare error rates with the pre-release baseline.
Some problems only appear under real traffic patterns or when caches warm up, so keep watching through a defined observation window.
Step 8: Roll back if the new version fails
Because the old environment is still running, rollback is another swap:
Identify the problem from health, events, and logs.
Run Actions → Swap environment URLs again, selecting the other environment (or use the CLI command above with source and destination reversed).
Verify that the production URL returns the previous version.
Investigate the root cause before attempting another release.
Two cautions. First, DNS caching works in both directions, so rollback isn't instantaneous for every client. Second, swapping environments does not undo database changes. If version 2.0.0 ran a migration that version 1.0.0 can't handle, swapping back may fail too. Plan for this in advance (see best practices).
Keep the previous environment running for an agreed rollback window. Don't terminate it just because the swap succeeded.
Step 9: Clean up and optimize
After the rollback window passes with no issues:
Confirm DNS has settled before terminating the old environment, as AWS recommends.
Check what the environment includes (load balancer, Auto Scaling group, instances) and make sure nothing else depends on it.
Review logs you want to keep and export them to S3 or CloudWatch Logs retention as needed.
Terminate the old environment, or scale it down if you keep a standing standby.
Clean up old application versions using a lifecycle policy to stay within quotas.
Running two complete environments permanently roughly doubles that infrastructure's cost, so many teams run the second environment only during releases and re-create it from a saved configuration or clone when needed. Compare this against your recovery needs and budget.
Automating Blue-Green Deployment with CI/CD
Manual swaps are fine for learning, but repeatable releases need automation. A typical pipeline:
Commit: a change merges to the main branch.
Build: install dependencies and package the app.
Test: run unit and integration tests.
Artifact: create a versioned ZIP and upload it to S3.
Deploy to Green: create an application version and update the Green environment.
Validate Green: wait for healthy status and run smoke tests against the Green URL.
Approve: require a manual approval or automated gate for production promotion.
Swap: exchange the environment URLs.
Monitor: verify production health after the swap and alert or roll back on failure.
Here is an illustrative GitHub Actions workflow. It assumes you've configured an IAM role for GitHub OIDC, repository variables, and a protected production environment that requires approval. Treat it as a starting point to adapt and test, not a drop-in implementation.
Two things this workflow does not do, deliberately:
It does not provide full automated rollback. A URL swap is only the mechanism. A reliable rollback system also needs decision logic: which metrics define "unhealthy," how long to observe, who is alerted, and whether an automatic swap-back is safe given the database state. You might wire CloudWatch alarms to a notification or a rollback job, but test that path carefully.
It does not solve database compatibility. That requires release design, not just pipeline steps.
For the pipeline's AWS role, start with least-privilege permissions for the specific actions it uses (such as elasticbeanstalk:CreateApplicationVersion, UpdateEnvironment, DescribeEnvironments, SwapEnvironmentCNAMEs, and s3:PutObject on the deploy bucket) and extend only as AWS requires, per the Elastic Beanstalk permissions documentation. AWS CodePipeline can implement the same stages if you prefer AWS-native orchestration.
Best Practices for Production Blue-Green Deployments
Keep Blue and Green configurations consistent. Use cloning or infrastructure as code so differences are intentional. Re-check security groups, scaling settings, and environment properties.
Validate Green before swapping. Use automated and manual tests against production-like conditions.
Use health checks and automated tests in the pipeline so promotion depends on evidence.
Make database changes backward compatible. Use an expand and contract approach: first add new columns or tables in a way both versions can use, deploy the application, and remove old structures only in a later release. This keeps rollback possible.
Avoid unsafe shared mutable state. Both environments may be running at once. Be careful with local file storage, in-memory sessions, background workers, and scheduled jobs that could run twice or conflict. Prefer external stores for sessions and uploads.
Protect secrets. Keep credentials in AWS Secrets Manager or Systems Manager Parameter Store rather than in code or bundles.
Apply least-privilege IAM to the instance profile, service role, and pipeline role.
Monitor logs and metrics before, during, and after the swap, with alarms on error rate and latency.
Retain the previous environment through a defined rollback window.
Document the procedures: how to deploy, swap, roll back, and who decides.
Manage the extra cost of the second environment by terminating or scaling it down when no longer needed.
Integrate with CI/CD so releases are repeatable and auditable.
Databases deserve special emphasis. Swapping environments redirects application traffic; it doesn't touch your data. If a release includes a schema change, the old version must still work against the new schema, or rolling back will break. This is why Blue-Green works best when the database is external to the Elastic Beanstalk environment, as AWS recommends.
Blue-Green vs. Other Deployment Strategies
Elastic Beanstalk also offers built-in deployment policies for updating an environment in place. Here is how they compare:
All at onceRollingImmutableBlue-Green (URL swap)ProcessDeploys to all instances simultaneouslyDeploys in batches (optionally with an additional batch)Launches new instances in a temporary group, then replaces old onesDeploys to a separate environment, then swaps URLsDowntime riskHighest; instances are out of service brieflyReduced capacity during deployment unless an additional batch is usedLow; old instances remain until new ones are healthyLow, but DNS caching and application behavior still matterRollbackRedeploy the previous versionRedeploy; a failed rolling update can leave a mix of versionsSimple; failed new instances are terminatedSwap back, with database caveatsInfrastructureNone extraNone extra, or a temporary extra batchTemporary doubling of instancesA full second environmentFlexibilitySimple, fastestModerateModerateHigh: test a full environment before releaseBest forDev/test, tolerant workloadsMany production appsProduction apps needing safe, clean releasesMajor releases, platform upgrades, strict validation needs
Elastic Beanstalk's traffic splitting policy is a separate option: it launches a full set of new instances like an immutable deployment, then sends a percentage of traffic to them for an evaluation period before shifting everything. It's closer to a canary release than a Blue-Green swap and requires an Application Load Balancer.
There's no single best choice. The right strategy depends on your architecture, availability requirements, team maturity, and budget. Many teams use immutable or rolling deployments for routine releases and reserve Blue-Green for larger, riskier changes such as platform upgrades.
Conclusion: Deliver Safer Releases with Blue-Green Deployment
Blue-Green Deployment in AWS Elastic Beanstalk lets you isolate a new release in its own environment, validate it under realistic conditions, and switch production traffic only when you're ready, with the previous environment kept as a fast path back. Combined with automated tests, monitoring, and a clear rollback plan, it turns risky releases into a controlled process.
It also has limits. A URL swap isn't gradual traffic shifting, DNS caching means the cutover isn't perfectly instant, and nothing in the swap protects your database. Reliable releases depend on more than a successful code push: they need thoughtful infrastructure, backward-compatible data changes, observability, and a well-rehearsed operational process.
AWS Infrastructure Security: Essential Practices for a Secure and Reliable Cloud Environment
Qbits
Tech Team
AWS Infrastructure Security: Essential Practices for a Secure and Reliable Cloud Environment
AWS Cost Optimization: A Practical Guide to Building Cost-Efficient Cloud Infrastructure Picture a SaaS company that launches on AWS with a modest setup: a...