AWS Elastic Beanstalk · MCP Server Deployment, Auto-Scaling & Blue/Green · 2026-11-21 · Elastic Beanstalk arc
AWS Elastic Beanstalk for MCP Servers: PORT=8080, Dockerrun.aws.json v3, Secrets Manager Hooks, ALB Sticky Sessions, and Blue/Green Deployment
MCP servers break the assumptions that make REST API deployments easy: SSE connections are long-lived and stateful, tool calls can run for seconds to minutes, CPU utilization stays low even under heavy load, and naive rolling deployments silently kill active client sessions. AWS Elastic Beanstalk — the managed PaaS layer that sits between App Runner's simplicity and ECS Fargate's control — handles all the underlying infrastructure, but only if you configure it for the specific demands of the MCP protocol. This guide synthesises four Elastic Beanstalk deployment guides for MCP server developers: the Node.js platform workflow and the PORT=8080 Procfile requirement that causes the most common first-deployment failure, the Docker platform's Dockerrun.aws.json v3 ECS syntax (not the deprecated v2), the Secrets Manager predeploy hook workaround that EB's native configuration model cannot provide, the ALB sticky session configuration required for stateful SSE sessions, the RollingWithAdditionalBatch deployment policy that protects active sessions during code pushes, and the eb swap blue/green pattern with the Route 53 manual step that the EB console doesn't mention.
Why Elastic Beanstalk is the right fit for most MCP server teams
MCP server teams face a placement problem when choosing AWS infrastructure. Lambda is too restrictive — it does not support long-lived HTTP connections, so SSE-based MCP servers cannot run on it without significant workarounds. ECS Fargate is the right long-term answer but requires task definitions, service files, ALB listener rules, target groups, and IAM roles to all be defined before the first deployment. App Runner is the simplest path but provides almost no configuration surface for the low-level nginx and Auto Scaling tuning that production MCP servers need.
Elastic Beanstalk occupies the gap between those extremes. You give it an application bundle — a zip of your source code, a Dockerfile, or an ECR image reference — and it orchestrates the EC2 fleet, Auto Scaling group, load balancer, CloudWatch log streaming, and rolling deployments. When you need to override defaults, you add .ebextensions/*.config YAML files or .platform/hooks/ shell scripts that run as root on each instance. You never write a CloudFormation template. You never manually configure a target group. You get the same underlying AWS infrastructure as ECS, just assembled and operated by EB's control plane.
That is the value proposition. The catch is that EB's defaults are designed for stateless web applications, and MCP servers are not stateless. Each section of this guide covers one place where the defaults need to change — and why getting it wrong silently breaks your MCP server in a way that health checks cannot detect.
The Node.js platform: PORT=8080 and the Procfile requirement
The EB Node.js platform guide documents the most common cause of health check failures on first EB deployment: port mismatch. EB's Node.js platform runs nginx as a reverse proxy on port 80 and proxies all traffic to your application on port 8080. At deployment time, EB injects the environment variable PORT=8080 into the application environment. If your MCP server hardcodes a port like 3000 or 4000, nginx cannot reach it. The ALB health check fails. The environment enters a degraded state. The EB console shows no obvious cause because the Node.js process itself started without error — it's just listening on the wrong port.
The correct pattern is a single-line change in your server entry point:
// Always read PORT from the environment — EB injects PORT=8080
const PORT = parseInt(process.env.PORT ?? '3000', 10);
httpServer.listen(PORT);
The fallback to 3000 is intentional — it allows local development without environment variable setup while ensuring EB's injected PORT=8080 takes precedence in production.
The Procfile addresses a different problem. Without one, EB's Node.js platform runs your application by executing npm start, which invokes package.json's scripts.start. A Procfile gives you explicit control:
# Procfile — explicit process command for EB's process supervisor
web: node dist/server.js
# Optional sidecar processes (do not receive HTTP traffic)
worker: node dist/worker.js
metrics: node dist/metrics-exporter.js
The web: process type is the HTTP-serving process wired up to nginx and the ALB health checker. Only one process can be web:. The others (worker:, metrics:) are started as separate OS processes by EB's Foreman-compatible supervisor but receive no traffic — they are useful for MCP server architectures that separate the HTTP handler from tool execution workers. The key advantage of Procfile over npm start: you can reference Node.js flags directly without shell quoting issues:
# Procfile with explicit Node.js memory and source-map settings
web: node --max-old-space-size=512 --enable-source-maps dist/server.js
Alongside the Procfile, the minimum .ebextensions/mcp.config that every MCP server needs:
# .ebextensions/mcp.config
option_settings:
aws:elasticbeanstalk:application:environment:
NODE_ENV: production
MCP_LOG_LEVEL: info
# Point health checks at /health, not / (many MCP servers don't serve GET /)
aws:elasticbeanstalk:application:
Application Healthcheck URL: /health
# Enhanced health agent reports CPU, process restarts, request metrics
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
HealthStreamingEnabled: true
HealthCheckSuccessThreshold: Ok
# Stream logs to CloudWatch — instances replaced during scale-in lose logs otherwise
aws:elasticbeanstalk:cloudwatch:logs:
StreamLogs: true
RetentionInDays: 30
DeleteOnTerminate: false
The Application Healthcheck URL: /health option matters for MCP servers. The default is /. Many MCP servers respond with 404 on GET requests to the root path because they only handle /sse and /message. With the default health check path, the ALB reports all instances as unhealthy seconds after the first deployment.
For high-traffic environments where the health check frequency (every 5–15 seconds from each ALB availability zone) adds measurable load to the Node.js event loop, serve the health response directly from nginx without proxying to Node.js:
# .ebextensions/nginx-health.config
files:
"/etc/nginx/conf.d/health.conf":
mode: "000644"
owner: root
group: root
content: |
location /health {
access_log off;
return 200 '{"status":"ok"}';
add_header Content-Type application/json;
}
This nginx snippet returns 200 without proxying to Node.js, which also makes the health check immune to Node.js event loop lag or garbage collection pauses that might otherwise cause spurious health check failures and unwanted instance replacements.
The Docker platform: port 80 (not 8080) and Dockerrun.aws.json v3
The EB Docker platform guide starts with the platform choice decision. The Node.js managed platform is the fastest path for a standard Node.js MCP server. The Docker platform is right when you need a non-Node.js runtime (Python MCP servers using the mcp PyPI package, Rust-based MCP servers), pinned system dependencies (FFmpeg, Pandoc, native binaries), exact Node.js patch version pinning, multi-stage TypeScript builds, or a sidecar process (Valkey for in-memory session state).
The critical difference from the Node.js platform that trips up developers who switch: the Docker platform does not inject PORT=8080. The EB nginx proxy on the Docker platform forwards to port 80 of the container by default. Your Dockerfile must expose port 80 (or you must configure the nginx upstream port via .ebextensions). The standard multi-stage Dockerfile for a TypeScript MCP server:
# Dockerfile — multi-stage TypeScript MCP server build
FROM node:20.18-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json tsconfig.json ./
RUN npm ci
COPY src/ ./src/
RUN npm run build # outputs to dist/
FROM node:20.18-alpine AS runtime
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
# Docker platform: port 80, not 8080 (no PORT=8080 injection)
EXPOSE 80
ENV NODE_ENV=production PORT=80
CMD ["node", "dist/server.js"]
When you pre-build images and push them to ECR, use Dockerrun.aws.json in place of a Dockerfile. This is where version awareness matters: use version 3, not version 2. The v2 format (which many Stack Overflow answers still reference) used a simplified container definition structure. The v3 format uses ECS task definition container definition syntax, which gives you full control over resource limits, environment variable injection, secrets resolution, and log configuration:
{
"AWSEBDockerrunVersion": "3",
"containerDefinitions": [
{
"name": "mcp-server",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/mcp-server:1.4.2",
"essential": true,
"memory": 512,
"memoryReservation": 256,
"portMappings": [
{ "hostPort": 80, "containerPort": 80, "protocol": "tcp" }
],
"environment": [
{ "name": "NODE_ENV", "value": "production" },
{ "name": "PORT", "value": "80" }
],
"secrets": [
{
"name": "ANTHROPIC_API_KEY",
"valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:mcp-server/anthropic-key-AbCd"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/aws/elasticbeanstalk/mcp-server-prod",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "mcp-server"
}
},
"healthCheck": {
"command": ["CMD-SHELL", "curl -sf http://localhost/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 60
}
}
]
}
The secrets array in Dockerrun.aws.json v3 resolves values from Secrets Manager at container start time — the ECS agent running on the EB instance handles the resolution. The EB instance profile needs secretsmanager:GetSecretValue on the secret ARN for this to work. Using :latest as the image tag is an anti-pattern for production: it makes rollback ambiguous and can mask which version is actually deployed. Use the git short SHA as the immutable tag:
IMAGE_TAG=$(git rev-parse --short HEAD)
ECR_URI="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${ECR_REPO}"
docker build --platform linux/amd64 -t "${ECR_URI}:${IMAGE_TAG}" .
aws ecr get-login-password --region "${REGION}" \
| docker login --username AWS --password-stdin "${ECR_URI}"
docker push "${ECR_URI}:${IMAGE_TAG}"
# Update Dockerrun.aws.json image field before eb deploy
jq --arg img "${ECR_URI}:${IMAGE_TAG}" \
'.containerDefinitions[0].image = $img' \
Dockerrun.aws.json > Dockerrun.aws.json.tmp \
&& mv Dockerrun.aws.json.tmp Dockerrun.aws.json
eb deploy mcp-server-prod --message "deploy ${IMAGE_TAG}"
The Docker platform also supports a multi-container sidecar pattern that works well for small MCP server deployments that need in-memory session state without the overhead of an ElastiCache cluster. Since all containers in a Dockerrun.aws.json v3 definition share the host network namespace, they communicate via localhost. A Valkey sidecar for session persistence:
// Dockerrun.aws.json — MCP server + Valkey sidecar
{
"AWSEBDockerrunVersion": "3",
"containerDefinitions": [
{
"name": "mcp-server",
"essential": true,
"environment": [{ "name": "REDIS_URL", "value": "redis://localhost:6379" }],
"dependsOn": [{ "containerName": "valkey", "condition": "START" }]
// ... rest of mcp-server definition
},
{
"name": "valkey",
"image": "public.ecr.aws/docker/library/valkey:7.2-alpine",
"essential": false,
"memory": 128,
"command": ["valkey-server", "--maxmemory", "100mb",
"--maxmemory-policy", "allkeys-lru", "--save", ""]
}
]
}
The dependsOn condition START means the MCP server container starts only after Valkey has started — not after it passes a health check. Use HEALTHY for the stricter guarantee (requires a healthCheck block on Valkey). The essential: false on Valkey means the task group continues if Valkey crashes; set it to true if your MCP server cannot function without session state persistence.
Secrets Manager integration: the predeploy hook workaround
The EB environment configuration guide documents a gap that catches developers who have used AWS CloudFormation: EB environment variables do not support {{resolve:secretsmanager:...}} dynamic references. That syntax is CloudFormation-specific. Setting ANTHROPIC_API_KEY: "{{resolve:secretsmanager:mcp-server/keys}}" in .ebextensions will pass the literal string — not the resolved value — to your Node.js process.
The correct workaround for the Node.js platform uses .platform/hooks/predeploy/ scripts. These scripts run as root on the EC2 instance after the application bundle is extracted but before the application starts. They can call AWS CLI commands, and they can write to EB's application environment file at /opt/elasticbeanstalk/deployment/env — which EB sources before starting the application process, making the values available as process.env.*:
#!/bin/bash
# .platform/hooks/predeploy/00-inject-secrets.sh
# Resolve Secrets Manager secrets into the EB application environment.
# EB does NOT natively support {{resolve:secretsmanager:...}} in .ebextensions.
set -euo pipefail
REGION="${AWS_REGION:-us-east-1}"
SECRET_NAME="mcp-server/production"
echo "Fetching secrets: ${SECRET_NAME}"
SECRET_JSON=$(aws secretsmanager get-secret-value \
--region "${REGION}" \
--secret-id "${SECRET_NAME}" \
--query SecretString \
--output text)
ANTHROPIC_API_KEY=$(echo "${SECRET_JSON}" | jq -r '.anthropic_api_key // empty')
DATABASE_URL=$(echo "${SECRET_JSON}" | jq -r '.database_url // empty')
for var in ANTHROPIC_API_KEY DATABASE_URL; do
if [ -z "${!var}" ]; then
echo "ERROR: required secret '${var,,}' missing from ${SECRET_NAME}" >&2
exit 1
fi
done
ENV_FILE="/opt/elasticbeanstalk/deployment/env"
sed -i '/^ANTHROPIC_API_KEY=/d;/^DATABASE_URL=/d' "${ENV_FILE}" 2>/dev/null || true
printf 'ANTHROPIC_API_KEY=%s\n' "${ANTHROPIC_API_KEY}" >> "${ENV_FILE}"
printf 'DATABASE_URL=%s\n' "${DATABASE_URL}" >> "${ENV_FILE}"
echo "Secrets injected from ${SECRET_NAME}"
Several things to get right for this script to work:
- The script file must be executable:
chmod +x .platform/hooks/predeploy/00-inject-secrets.shand committed with those permissions. - The EB instance profile (
aws-elasticbeanstalk-ec2-role) must havesecretsmanager:GetSecretValueon the secret ARN. Without it, the script exits non-zero, failing the deployment — which is the correct behavior, since starting without secrets would produce a broken MCP server. jqmust be available on the instance. Install it in.ebextensionswithpackages: { yum: { jq: [] } }.- The
sed -iremoves any existing entries before appending to avoid duplicates across redeployments of the same environment.
The predeploy vs postdeploy distinction in .platform/hooks/ matters for reliability. Scripts in predeploy/ run before the application starts — if they exit non-zero, the deployment fails and EB rolls back. Use predeploy/ for anything that must succeed before traffic is served: secrets injection, schema migrations, configuration validation. Scripts in postdeploy/ run after the application starts and passes health checks — if they exit non-zero, they emit a warning but do not fail the deployment or roll back. Use postdeploy/ for non-critical notifications (SNS deployment alerts, dashboard updates, metric resets). The numeric prefix controls execution order within each directory — 00-inject-secrets.sh runs before 01-validate-environment.sh.
For the Docker platform, the Dockerrun.aws.json v3 secrets array handles Secrets Manager resolution natively — the ECS agent resolves the ARN at container start time. The predeploy hook workaround is specific to the Node.js managed platform where there is no ECS agent to perform that resolution.
ALB vs CLB: why SSE-based MCP servers require the Application Load Balancer
The EB autoscaling guide explains why MCP server auto-scaling is different from REST API scaling — and the first decision point that determines whether SSE transport works at all: load balancer type.
EB supports three load balancer types. The Classic Load Balancer (CLB) is the legacy default. It has a maximum idle connection timeout of 4000 seconds, but — critically — it closes long-lived SSE connections at its idle timeout. An SSE connection where no data has flowed for 60 seconds (the CLB default) will be terminated, dropping the client's MCP session. Beyond the timeout problem, the CLB lacks HTTP/2 multiplexing, WebSocket upgrade support, and path-based routing rules. It cannot route /sse to one target group and /health to another. Do not use CLB for MCP servers.
The Application Load Balancer (ALB) supports HTTP/2 multiplexing, WebSocket upgrades, SSE connections with configurable idle timeout up to 4000 seconds, path-based routing rules, and the AWSALB sticky session cookie. Configure the ALB in .ebextensions:
# .ebextensions/alb.config
option_settings:
# Must be set at environment creation — cannot change LB type on existing environment
aws:elasticbeanstalk:environment:
LoadBalancerType: application
# Increase idle timeout for long-lived SSE connections (default is 60s)
aws:elbv2:loadbalancer:
IdleTimeout: 3600 # 1 hour; max is 4000s
# ALB access logs (useful for diagnosing SSE disconnects)
aws:elbv2:loadbalancer:
AccessLogsS3Enabled: true
AccessLogsS3Bucket: my-alb-logs-bucket
AccessLogsS3Prefix: mcp-server-prod
The LoadBalancerType option cannot be changed on an existing environment — it is set at environment creation time. If you created an environment with the CLB default and need to switch, you must create a new environment with LoadBalancerType: application and deploy to it. The blue/green swap pattern (covered below) is the right tool for this migration.
Also configure nginx for SSE transport. The critical nginx directive is proxy_buffering off: nginx's default response buffering accumulates SSE events and delivers them in batches rather than streaming them immediately to the client, breaking SSE protocol semantics:
# .ebextensions/nginx-sse.config
files:
"/etc/nginx/conf.d/sse.conf":
mode: "000644"
owner: root
group: root
content: |
location /sse {
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
ALB sticky sessions: pinning SSE clients to their instance
The stateful nature of MCP server SSE connections creates a problem for multi-instance environments: if a client's subsequent requests (the POST /message calls that follow the initial GET /sse connection) are load-balanced to a different instance than the one holding their session, the second instance has no context for the session and returns an error.
ALB sticky sessions solve this by embedding the target instance ID in a cookie (AWSALB) that the ALB sets on the first response. All subsequent requests from that client bearing the cookie are routed to the same instance. Enable sticky sessions on the target group:
# .ebextensions/sticky-sessions.config
option_settings:
aws:elbv2:targetgroup:default:
StickinessEnabled: true
# Duration before the stickiness cookie expires and the client can be
# rebalanced. 86400s = 24 hours. Match to your expected MCP session lifetime.
StickinessLBCookieDurationSeconds: 86400
# Listener rule stickiness (required in addition to target group stickiness)
aws:elbv2:listenerrule:default:
StickinessEnabled: true
The AWSALB cookie is set by the ALB itself — your MCP server does not need to do anything. For CORS-enabled deployments (MCP servers accessed from web applications on a different domain), the ALB also sets the AWSALBCORS cookie with SameSite=None; Secure. Your MCP server must respond with Access-Control-Allow-Credentials: true for the browser to include the cookie on cross-origin SSE requests.
Important caveat: sticky sessions require the client to persist and send cookies. Claude Desktop, Cursor, and MCP clients using the official SDK handle this correctly. For programmatic clients that do not persist cookies between requests, sticky sessions will not work — consider URL-based session routing (a path prefix encoding the instance ID) or an external ElastiCache session store accessible to all instances.
When an instance is deregistered from the target group (during scale-in or deployment), existing sticky session cookies pointing to that instance are honored during the ALB's deregistration delay. After the delay expires, those connections are closed. Configure the delay based on your P99 tool call duration:
option_settings:
aws:elbv2:targetgroup:default:
# Default 300s. Tune to match P99 tool call duration.
# Too low: aborts long-running tool calls during scale-in
# Too high: slows down scale-in significantly (300s × instances being removed)
DeregistrationDelay: "300"
Deployment policy: RollingWithAdditionalBatch protects active sessions
EB's default deployment policy is AllAtOnce: take all instances out of service simultaneously, deploy the new version, bring them back. For a production MCP server with active SSE sessions, this destroys every active client session during every deployment. The fix is a deployment policy that keeps some instances serving traffic throughout:
# .ebextensions/deployment.config
option_settings:
aws:elasticbeanstalk:command:
# RollingWithAdditionalBatch: adds new instances BEFORE terminating old ones.
# - Never reduces capacity below MinSize during deployment
# - Active MCP sessions on old instances continue until ALB drains them
# - New instances become healthy before old ones leave the target group
DeploymentPolicy: RollingWithAdditionalBatch
BatchSizeType: Percentage
BatchSize: "25" # 25% = 1 instance per batch for a 4-instance fleet
# Time EB waits for new batch to pass health checks before continuing
# Must be long enough for npm install + MCP server startup time
Timeout: "600"
IgnoreHealthCheck: false
How RollingWithAdditionalBatch works for a 4-instance fleet with BatchSize: 25: EB temporarily scales up to 5 instances, deploys the new version on the extra instance, waits for it to pass health checks, then terminates instance 1 (the oldest). The fleet returns to 4 instances, all running the new version after 4 batches. Throughout this process, 3–4 instances are always serving traffic. Active sessions on the old version instances continue until the ALB's DeregistrationDelay expires — the same 300-second window that protects in-flight tool calls during scale-in.
The alternative Immutable deployment policy creates a completely new Auto Scaling group, deploys the new version there, waits for health checks, then terminates the old group. This provides the strongest session protection (old instances serve traffic until they are terminated, not drained) but doubles the instance count during deployment, increasing cost. For MCP servers where deployment-time session disruption is a hard requirement to avoid, Immutable is the right choice; for most teams, RollingWithAdditionalBatch is the right balance.
Scaling trigger: NetworkOut over CPUUtilization for I/O-bound MCP servers
Auto Scaling trigger selection is specific to MCP server workload profiles. MCP proxy servers — those that orchestrate calls to Bedrock, OpenAI, external databases, or other APIs — spend most of their time waiting on I/O. The Node.js event loop is unblocked and CPU utilization stays low even when the instance is handling hundreds of concurrent SSE connections each waiting on a Bedrock response. A CPUUtilization trigger at 70% will never fire for these workloads, leaving the fleet under-scaled during load spikes.
# .ebextensions/autoscaling.config — NetworkOut trigger for I/O-bound MCP servers
option_settings:
aws:autoscaling:asg:
MinSize: 2 # Always at least 2 for HA — single instance = single point of failure
MaxSize: 10
Cooldown: 300
aws:autoscaling:trigger:
MeasureName: NetworkOut
Unit: Bytes
Statistic: Average
Period: "5" # 5-minute average smooths transient spikes
BreachDuration: "2" # Must stay above threshold for 2 minutes before scaling out
UpperThreshold: "10000000" # 10 MB/5min avg → scale out
LowerThreshold: "1000000" # 1 MB/5min avg → scale in
UpperBreachScaleIncrement: "2"
LowerBreachScaleIncrement: "-1"
For compute-intensive MCP servers — those running local embedding models, code execution sandboxes, or image processing — CPUUtilization is the correct trigger. For mixed workloads, consider a custom CloudWatch metric that tracks active SSE connection count, which directly correlates with the work the server is actually doing regardless of whether that work is CPU or I/O bound.
Blue/green deployment via eb swap: the Route 53 step that EB doesn't mention
The environment configuration guide covers blue/green deployment as the strongest zero-downtime deployment pattern. The workflow: run two complete EB environments in parallel (blue = current production, green = new version), route users to blue while green warms up, then swap the URLs atomically. This eliminates the risk of rolling updates on the production environment — the green environment can be fully tested against production traffic patterns before any real users see it.
# Blue/green deployment workflow
# Step 1: Create the green environment with the same saved configuration
eb create mcp-server-green \
--cfg prod-baseline \
--tags Environment=green,Service=mcp-server
# Step 2: Deploy new version to green only
eb deploy mcp-server-green --message "v1.5.0 release candidate"
# Step 3: Smoke-test the green environment's URL
GREEN_URL=$(aws elasticbeanstalk describe-environments \
--environment-names mcp-server-green \
--query 'Environments[0].CNAME' --output text)
curl "https://${GREEN_URL}/health"
# {"status":"ok","version":"1.5.0"}
# Step 4: Atomic CNAME swap — green becomes production
eb swap mcp-server-prod --destination_name mcp-server-green
# Step 5: If problems appear, swap back:
eb swap mcp-server-prod --destination_name mcp-server-green
# Step 6: Terminate old environment after confidence period
eb terminate mcp-server-green
The eb swap command swaps the EB-assigned .elasticbeanstalk.com subdomain between the two environments. The swap completes in 1–2 minutes. What EB's documentation does not emphasize: if your MCP server is behind a custom domain with Route 53, the eb swap does not update your Route 53 records. The ALIAS or CNAME record pointing at mcp-server-prod.{region}.elasticbeanstalk.com now resolves to the old blue environment (which is still running but on the green subdomain after the swap). You must manually update the Route 53 record to point at the new mcp-server-prod subdomain after the swap completes.
Alternatively, if your Route 53 record points at the EB subdomain by name rather than by environment name — for example, using an ALIAS to mcp-server-prod.us-east-1.elasticbeanstalk.com — then the swap is transparent because the mcp-server-prod subdomain moves to the green environment after the swap. Test your DNS setup before relying on this behavior in production.
Sticky session behavior during the swap
Active SSE sessions on the blue environment are not automatically migrated to green during the swap. After the CNAME swap, existing sticky session cookies point to the blue environment's target instances. The ALB uses the target instance ID encoded in the cookie — after the swap, those cookies still route to the old blue instances until the cookie expires or the instance is terminated. This is actually desirable: existing sessions continue on blue until they naturally expire, while new clients get the new version. After 24 hours (the default sticky session TTL), all active sessions will be on the new version.
.ebextensions vs .platform/hooks/: choosing the right customization mechanism
EB provides two customization mechanisms that overlap in capability but have different strengths and appropriate uses.
.ebextensions/*.config files are YAML documents that EB processes in alphabetical order during each deployment. They support five sections: option_settings (EB namespace/option pairs), files (create or update files on the EC2 instance), packages (install OS packages), commands (run before app bundle extraction), and container_commands (run after extraction, with leader_only: true for database migrations). Use .ebextensions for EB configuration options, OS package installation, nginx configuration files, and one-time setup commands. The container_commands section with leader_only: true is the right place for database migrations in multi-instance deployments — it runs exactly once per deployment on the leader instance:
# .ebextensions/migrations.config
container_commands:
01-run-db-migrations:
command: |
timeout 300 node dist/migrate.js up || {
echo "Migration failed or timed out" >&2
exit 1
}
leader_only: true
env:
NODE_ENV: production
.platform/hooks/ scripts are shell files in three subdirectories (prebuild/, predeploy/, postdeploy/) that run as root at specific points in the deployment lifecycle. They are available on the Amazon Linux 2023 platform family. Use .platform/hooks/ for Secrets Manager injection, complex pre-flight validation, and post-deployment notifications. The key advantage over .ebextensions commands: hooks run in a predictable lifecycle stage relative to the application, and their pass/fail semantics are more explicit (predeploy failures abort the deployment; postdeploy failures warn but do not roll back).
The two mechanisms work together. A typical production MCP server configuration uses .ebextensions for all option_settings blocks, nginx configuration files, and OS package installation, while .platform/hooks/predeploy/ handles Secrets Manager injection and .platform/hooks/postdeploy/ handles deployment notifications.
Saved configurations: staging/production parity
EB's saved configurations let you snapshot an environment's option settings and reuse them to create new environments with identical configuration. This is the EB equivalent of Infrastructure-as-Code for environment settings:
# Save the current production environment's configuration as a baseline
eb config save mcp-server-prod --cfg prod-baseline
# Apply the saved configuration to a new staging environment
eb create mcp-server-staging \
--cfg prod-baseline \
--tags Environment=staging
# Update the saved configuration after a configuration change
eb config save mcp-server-prod --cfg prod-baseline
Saved configurations are stored in S3 and checked into .elasticbeanstalk/saved_configs/ in your project. They are the right tool for ensuring that the staging environment that validated your code change uses the same ALB settings, Auto Scaling trigger, deployment policy, and enhanced health configuration as production. The pattern of "create green from prod-baseline, deploy, test, swap" only works as a true blue/green if green and blue have identical configurations — saved configurations enforce that.
Failure patterns table: what goes wrong and why
| Symptom | Root cause | Fix |
|---|---|---|
| Environment enters Degraded on first deployment, no obvious error | MCP server listening on hardcoded port 3000/4000, not process.env.PORT (8080) |
Use const PORT = parseInt(process.env.PORT ?? '3000', 10) |
| All instances show Unhealthy despite server starting successfully | Application Healthcheck URL left at default /; MCP server returns 404 on GET / |
Set Application Healthcheck URL: /health in .ebextensions |
| SSE connections drop after 60 seconds on idle sessions | Classic Load Balancer idle timeout; ALB not configured | Set LoadBalancerType: application; set IdleTimeout: 3600 |
| SSE events arrive in bursts instead of streaming continuously | nginx proxy buffering enabled (default) | Add proxy_buffering off; to nginx /sse location block |
| Clients lose session context mid-conversation after scale-out | Sticky sessions not configured; new instance gets POST /message with no context | Enable StickinessEnabled: true on target group |
| Deployment kills all active MCP sessions simultaneously | DeploymentPolicy: AllAtOnce (default) |
Use DeploymentPolicy: RollingWithAdditionalBatch |
Secrets Manager values arrive as literal {{resolve:...}} strings |
EB does not resolve CloudFormation dynamic references in env vars | Use .platform/hooks/predeploy/00-inject-secrets.sh to write to /opt/elasticbeanstalk/deployment/env |
| Docker deployment fails to pull ECR image | Instance profile missing ecr:GetAuthorizationToken (must have Resource: *) or ecr:BatchGetImage |
Add ECR pull policy to aws-elasticbeanstalk-ec2-role |
| Fleet never scales out despite high load | MeasureName: CPUUtilization for I/O-bound MCP proxy server; CPU stays low while waiting on external APIs |
Switch to MeasureName: NetworkOut |
Custom domain stops resolving after eb swap |
Route 53 ALIAS/CNAME points to environment name; eb swap does not update Route 53 records |
Manually update Route 53 record to new environment CNAME after swap |
| Dockerrun.aws.json v3 container secrets not resolved | Instance profile missing secretsmanager:GetSecretValue; ECS agent cannot resolve valueFrom ARNs |
Add Secrets Manager read policy to EB EC2 instance role |
Complete production configuration: the full .ebextensions stack
A production MCP server on EB uses multiple .ebextensions files and at least one .platform hook. Here is the directory structure and the key contents:
project/
├── server.js # MCP server: listens on process.env.PORT
├── package.json
├── package-lock.json
├── Procfile # web: node server.js
├── .ebignore # exclude node_modules, .env, src/
├── .ebextensions/
│ ├── 01-app.config # option_settings: health, enhanced health, CloudWatch logs
│ ├── 02-alb.config # LoadBalancerType: application, IdleTimeout: 3600
│ ├── 03-sticky.config # StickinessEnabled: true, 86400s duration
│ ├── 04-autoscaling.config # MinSize: 2, MaxSize: 10, NetworkOut trigger
│ ├── 05-deployment.config # DeploymentPolicy: RollingWithAdditionalBatch
│ ├── 06-nginx-sse.config # files: /etc/nginx/conf.d/sse.conf (proxy_buffering off)
│ └── 07-iam.config # IamInstanceProfile: aws-elasticbeanstalk-ec2-role
└── .platform/
└── hooks/
├── predeploy/
│ └── 00-inject-secrets.sh # Secrets Manager → /opt/elasticbeanstalk/deployment/env
└── postdeploy/
└── 01-notify-deploy.sh # SNS notification (non-fatal if fails)
The deployment sequence for a first-time production environment:
# 1. Initialize application (Node.js 20 on Amazon Linux 2023)
eb init mcp-server-app \
--platform "Node.js 20 running on 64bit Amazon Linux 2023" \
--region us-east-1
# 2. Create production environment with ALB
eb create mcp-server-prod \
--elb-type application \
--instance-type t3.medium \
--min-instances 2 \
--max-instances 10 \
--tags Environment=production,Service=mcp-server
# 3. Wait for Ready status, verify health
eb status mcp-server-prod
curl https://mcp-server-prod.us-east-1.elasticbeanstalk.com/health
# 4. Save production configuration for staging/green environment reuse
eb config save mcp-server-prod --cfg prod-baseline
# 5. For subsequent deployments
eb deploy mcp-server-prod --message "feat: add search tool"
Connect AliveMCP to monitor the /health endpoint at https://mcp-server-prod.us-east-1.elasticbeanstalk.com/health for external uptime tracking. EB's enhanced health reporting only surfaces instance-level metrics inside the EB console — an external check at AliveMCP catches network-level failures (misconfigured ALB listener rules, certificate expiry, DNS resolution failures, CDN edge errors) that EB's internal health agent cannot observe. Configure a 2-failure threshold to avoid noise from brief instance replacement events during scaling and rolling deployments.