Guide · AWS Elastic Beanstalk · Environment Configuration
Elastic Beanstalk Environment Configuration for MCP Servers — .ebextensions, Platform Hooks, and Blue/Green Deployment
Elastic Beanstalk's configuration model — .ebextensions YAML files processed at deploy time, .platform/hooks/ lifecycle scripts that run as root, saved configurations for environment templating, and atomic URL swaps for blue/green deployments — gives MCP server teams fine-grained control over the runtime environment without writing CloudFormation. This guide covers all five .ebextensions sections in depth, the namespace reference for MCP servers, the .platform/hooks/ directory for pre/post-deploy scripting, the Secrets Manager integration workaround, saved configurations for staging/production parity, and blue/green deployment via CNAME swap. For the initial deployment workflow, see Elastic Beanstalk Node.js Platform. For Docker platform configuration, see EB Docker Platform. For auto-scaling configuration, see EB Auto-Scaling.
TL;DR
Put all environment settings in .ebextensions/*.config YAML files processed alphabetically. Use .platform/hooks/predeploy/00-inject-secrets.sh to pull Secrets Manager values into the application environment — EB does not natively resolve {{resolve:secretsmanager:...}} in environment variables. For zero-downtime releases, use eb swap to atomically swap the green environment's URL to production. Save configurations with eb config save for staging/production environment templating.
.ebextensions deep dive: five sections
The .ebextensions/ directory contains .config files in YAML format. EB processes them in alphabetical order during each deployment, after extracting the application bundle but before starting the application. Each config file can contain any combination of five top-level sections:
# .ebextensions/00-reference.config — section reference
# 1. option_settings: EB namespace/option pairs controlling environment config
option_settings:
aws:elasticbeanstalk:application:environment:
NODE_ENV: production
# 2. files: create or update files on the EC2 instance
files:
"/etc/nginx/conf.d/mcp-custom.conf":
mode: "000644"
owner: root
group: root
content: |
location /sse {
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_pass http://127.0.0.1:8080;
}
# 3. packages: install OS packages before application starts
packages:
yum:
jq: []
git: []
# 4. commands: shell commands run BEFORE application bundle extraction
# runs as root on every deployment
commands:
01-set-timezone:
command: "timedatectl set-timezone UTC"
ignoreErrors: false
02-create-log-dir:
command: "mkdir -p /var/log/mcp-server"
# 5. container_commands: run AFTER app bundle extraction
# working directory is /var/app/staging/; can use leader_only
container_commands:
01-run-migrations:
command: "node dist/migrate.js"
leader_only: true
env:
NODE_ENV: production
The critical difference between commands and container_commands: commands run before the application bundle is extracted to /var/app/staging/, so they cannot reference files in your bundle. container_commands run with the working directory set to /var/app/staging/, so they can reference your compiled code, run database migrations, or validate configuration files. Both sections run on every deployment even if the relevant files have not changed.
Use the test key to run commands conditionally:
container_commands:
01-run-migrations:
command: "node dist/migrate.js"
leader_only: true
test: "[ -f /var/app/staging/dist/migrate.js ]"
Namespace reference for MCP server configuration
EB's configuration model is organized into namespaces. The namespaces most relevant to MCP server deployment:
# .ebextensions/app.config — namespace reference for MCP servers
option_settings:
# Application environment variables (accessible as process.env.*)
aws:elasticbeanstalk:application:environment:
NODE_ENV: production
MCP_LOG_LEVEL: info
MCP_SERVER_VERSION: "1.4.2"
# Health reporting with CloudWatch streaming
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
HealthStreamingEnabled: true
HealthCheckSuccessThreshold: Ok
# nginx proxy settings
aws:elasticbeanstalk:environment:proxy:
ProxyServer: nginx
GzipCompression: true
# Serve static assets directly from nginx (bypasses Node.js for /assets/*)
aws:elasticbeanstalk:environment:proxy:staticfiles:
/assets: dist/public/assets
# Launch template settings
aws:autoscaling:launchtemplate:
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
InstanceType: t3.medium
# Mixed instance policy with spot instances for cost optimization
aws:ec2:instances:
InstanceTypes: "t3.medium,t3a.medium,t3.large"
SpotFleetOnDemandBase: "1"
SpotFleetOnDemandAboveBasePercentage: "0"
# CloudWatch Logs streaming for application logs
aws:elasticbeanstalk:cloudwatch:logs:
StreamLogs: true
RetentionInDays: 30
DeleteOnTerminate: false
# CloudWatch Logs for health event streaming
aws:elasticbeanstalk:cloudwatch:logs:health:
HealthStreamingEnabled: true
RetentionInDays: 7
DeleteOnTerminate: false
# Managed platform updates (auto-apply security patches)
aws:elasticbeanstalk:managedactions:
ManagedActionsEnabled: true
PreferredStartTime: "Tue:03:00"
aws:elasticbeanstalk:managedactions:platformupdate:
UpdateLevel: minor
InstanceRefreshEnabled: true
The aws:elasticbeanstalk:environment:proxy:staticfiles namespace maps URL path prefixes to directories in your bundle. This allows nginx to serve static assets directly without proxying to Node.js — useful for MCP server dashboards or documentation sites co-located with the MCP server process.
.platform/hooks/: lifecycle scripts for Amazon Linux 2023
The .platform/hooks/ directory provides ordered shell script execution at three points in the deployment lifecycle. It is available on the Amazon Linux 2023 platform family and replaces some of the older .ebextensions commands patterns with a more auditable structure:
.platform/
└── hooks/
├── prebuild/ # before application source is downloaded
│ └── 01-install-system-deps.sh
├── predeploy/ # after source download, before app starts
│ ├── 00-inject-secrets.sh
│ └── 01-validate-environment.sh
└── postdeploy/ # after app starts and passes health check
└── 01-notify-deployment.sh
Each hook script must be executable (chmod +x). EB runs hooks as root. The numeric prefix controls execution order within each subdirectory. Hook scripts that exit with a non-zero status code fail the deployment — be careful with error handling:
#!/bin/bash
# .platform/hooks/postdeploy/01-notify-deployment.sh
# Send a deployment notification after the app passes health checks
set -euo pipefail
EB_ENV_NAME="${ENVIRONMENT_NAME:-unknown}"
APP_VERSION="${APP_VERSION:-unknown}"
REGION="${AWS_REGION:-us-east-1}"
# Publish to an SNS topic for deployment notifications
aws sns publish \
--region "${REGION}" \
--topic-arn "arn:aws:sns:us-east-1:123456789012:mcp-deployments" \
--subject "Deployment complete: ${EB_ENV_NAME}" \
--message "MCP server version ${APP_VERSION} deployed to ${EB_ENV_NAME}" \
|| echo "Warning: SNS notification failed (non-fatal)"
Note the || echo pattern on the SNS call — post-deploy notifications should not fail the deployment if the notification itself fails. Use this pattern for non-critical post-deploy steps. For critical steps (database migrations that must succeed before traffic is served), use predeploy/ hooks and let them fail the deployment if they exit non-zero.
Secrets Manager integration via predeploy hooks
AWS CloudFormation supports {{resolve:secretsmanager:...}} dynamic references in resource properties, but Elastic Beanstalk environment variables do not support this syntax. Setting MY_SECRET: "{{resolve:secretsmanager:my-secret}}" in .ebextensions will pass the literal string — not the resolved value — to your Node.js process. The workaround: use a predeploy hook to call Secrets Manager and write the values to EB's application environment file.
#!/bin/bash
# .platform/hooks/predeploy/00-inject-secrets.sh
# Resolve Secrets Manager secrets into the EB application environment.
# This runs before the application starts on each deployment.
set -euo pipefail
REGION="${AWS_REGION:-us-east-1}"
SECRET_NAME="mcp-server/production"
echo "Fetching secrets from Secrets Manager: ${SECRET_NAME}"
# Retrieve the secret (a JSON object with key/value pairs)
SECRET_JSON=$(aws secretsmanager get-secret-value \
--region "${REGION}" \
--secret-id "${SECRET_NAME}" \
--query SecretString \
--output text)
if [ -z "${SECRET_JSON}" ]; then
echo "ERROR: Failed to retrieve secret ${SECRET_NAME}" >&2
exit 1
fi
# Parse individual keys from the JSON secret
ANTHROPIC_API_KEY=$(echo "${SECRET_JSON}" | jq -r '.anthropic_api_key // empty')
DATABASE_URL=$(echo "${SECRET_JSON}" | jq -r '.database_url // empty')
WEBHOOK_SECRET=$(echo "${SECRET_JSON}" | jq -r '.webhook_secret // empty')
# Validate required secrets are present
for var in ANTHROPIC_API_KEY DATABASE_URL WEBHOOK_SECRET; do
if [ -z "${!var}" ]; then
echo "ERROR: Required secret key '${var,,}' missing from ${SECRET_NAME}" >&2
exit 1
fi
done
# Write to EB's application environment file.
# /opt/elasticbeanstalk/deployment/env is sourced before the app starts.
ENV_FILE="/opt/elasticbeanstalk/deployment/env"
# Remove any existing entries to avoid duplicates across deployments
sed -i '/^ANTHROPIC_API_KEY=/d;/^DATABASE_URL=/d;/^WEBHOOK_SECRET=/d' \
"${ENV_FILE}" 2>/dev/null || true
# Append new values (use printf to avoid issues with special characters)
printf 'ANTHROPIC_API_KEY=%s\n' "${ANTHROPIC_API_KEY}" >> "${ENV_FILE}"
printf 'DATABASE_URL=%s\n' "${DATABASE_URL}" >> "${ENV_FILE}"
printf 'WEBHOOK_SECRET=%s\n' "${WEBHOOK_SECRET}" >> "${ENV_FILE}"
echo "Secrets injected successfully from ${SECRET_NAME}"
The EB instance role needs secretsmanager:GetSecretValue on the secret ARN for this script to function. The values written to /opt/elasticbeanstalk/deployment/env are sourced by EB's application start script, making them available as process.env.ANTHROPIC_API_KEY etc. in your MCP server Node.js process.
Security note: the secret values are briefly stored in plaintext in /opt/elasticbeanstalk/deployment/env on the EC2 instance filesystem. Ensure the EB instance's EBS volume is encrypted (configure the launch template to use an encrypted root volume in .ebextensions), and restrict SSH access to the EB environment.
container_commands with leader_only for database migrations
Multi-instance MCP server deployments that use a shared database need to run schema migrations exactly once per deployment, not once per instance. The leader_only: true attribute in container_commands ensures the command runs only on the leader instance (the first instance in the Auto Scaling group at the time of deployment):
# .ebextensions/migrations.config
container_commands:
01-run-db-migrations:
command: "node dist/migrate.js up"
leader_only: true
# Timeout for the migration command (seconds)
# Default is no timeout — migrations that hang block deployment indefinitely
# Set an explicit timeout via the shell
command: |
timeout 300 node dist/migrate.js up || {
echo "Migration failed or timed out" >&2
exit 1
}
env:
NODE_ENV: production
The leader election is per-deployment, not persistent — the leader instance for one deployment may be a different physical instance than the leader for the next deployment. If a migration applies to the shared database, it will run once during each deployment where you include this container_commands block. Use idempotent migration scripts (or a migrations library that tracks which migrations have already run, like db-migrate or Drizzle Kit's migrate command) to make this safe across repeated deployments.
Saved configurations: templating staging and production
EB's saved configurations let you snapshot an environment's option_settings and reuse them to create new environments with the same configuration. This is the EB equivalent of Infrastructure-as-Code for environment settings:
# Save the current production environment's configuration
eb config save mcp-server-prod --cfg prod-baseline
# This creates:
# .elasticbeanstalk/saved_configs/prod-baseline.cfg.yml
# (also uploaded to S3 in the EB artifacts bucket)
# Contents of prod-baseline.cfg.yml (abbreviated):
# EnvironmentConfigurationMetadata:
# Description: Production baseline for mcp-server
# DateCreated: "2026-11-21T00:00:00.000Z"
# Platform:
# PlatformArn: arn:aws:elasticbeanstalk:us-east-1::platform/Node.js 20.../6.3.1
# OptionSettings:
# aws:autoscaling:asg:
# MinSize: '2'
# MaxSize: '10'
# aws:elasticbeanstalk:application:environment:
# NODE_ENV: production
# MCP_LOG_LEVEL: info
# ...
# Apply a saved configuration to an existing environment
eb config put prod-baseline
eb setenv --environment mcp-server-staging # apply to staging env
# Create a new environment using the saved configuration
eb create mcp-server-staging-v2 --cfg prod-baseline \
--tags Environment=staging
Saved configurations are stored in S3 at s3://elasticbeanstalk-{region}-{account-id}/resources/environments/mcp-server-app/. They are version-controlled — you can list all saved configurations with aws elasticbeanstalk list-available-solution-stacks (not quite right — use aws elasticbeanstalk describe-configuration-settings):
# List saved configurations for an EB application
aws elasticbeanstalk describe-application-versions \
--application-name mcp-server-app \
--query 'ApplicationVersions[*].{Version:VersionLabel,Date:DateCreated}' \
--output table
# Retrieve a saved configuration's option settings
aws elasticbeanstalk describe-configuration-settings \
--application-name mcp-server-app \
--template-name prod-baseline \
--query 'ConfigurationSettings[0].OptionSettings[*].{Namespace:Namespace,Name:OptionName,Value:Value}' \
--output table
Blue/green deployment via CNAME swap
Blue/green deployment for MCP servers means: 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 deployment-time risk of rolling updates on the production environment — the green environment can be fully tested and warmed before any production traffic sees it.
# Blue/green deployment workflow for MCP servers
# Step 1: Create the green environment (new version)
# Green starts with the same saved configuration as production
eb create mcp-server-green \
--cfg prod-baseline \
--tags Environment=green,Service=mcp-server
# Step 2: Deploy the new MCP server version to green
eb deploy mcp-server-green --message "v1.5.0 release candidate"
# Step 3: Run smoke tests against 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"}
# Run integration tests against the green environment
# npm run test:integration -- --base-url "https://${GREEN_URL}"
# Step 4: Atomic CNAME swap — green becomes production
# mcp-server-prod currently points to mcp-server-prod.{region}.elasticbeanstalk.com
# mcp-server-green currently points to mcp-server-green.{region}.elasticbeanstalk.com
# After swap: they exchange CNAMEs
eb swap mcp-server-prod --destination_name mcp-server-green
# The swap completes in 1-2 minutes.
# mcp-server-prod now serves the new version.
# mcp-server-green still runs the old version (now on the green URL).
# Step 5: Monitor production for 15-30 minutes
# If problems appear, swap back:
eb swap mcp-server-prod --destination_name mcp-server-green
# Step 6: Terminate the old green environment after confidence period
eb terminate mcp-server-green
The eb swap command swaps the EB-assigned .elasticbeanstalk.com subdomain (the CNAME). If your MCP server is behind a custom domain with Route 53, you must separately update the Route 53 record to point at the new EB CNAME. The EB swap itself takes 1–2 minutes and may cause a brief period (a few seconds) where DNS resolves to either environment — build retry logic into your MCP clients or use Route 53's weighted routing to gradually shift traffic.
Blue/green with sticky sessions
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 (now on the green URL) until they naturally expire, while new clients get routed to the new version. After 24 hours (the default sticky session TTL), all active sessions will be on the new version.
Managed platform updates
EB's managed platform updates automatically apply minor version patches (Node.js runtime security fixes, nginx updates, OS patches) to your environment during a maintenance window. This is distinct from an application deployment — EB performs a rolling instance replacement with the patched AMI, using the same rolling update policy configured in your environment.
# .ebextensions/managed-updates.config
option_settings:
aws:elasticbeanstalk:managedactions:
# Enable managed updates
ManagedActionsEnabled: true
# Maintenance window: day:HH:MM in UTC
# Choose off-peak hours for your user base
PreferredStartTime: "Tue:03:00"
aws:elasticbeanstalk:managedactions:platformupdate:
# minor: apply patch and minor versions (e.g., Node.js 20.11.0 -> 20.18.1)
# patch: apply patch versions only (e.g., 20.18.0 -> 20.18.1)
UpdateLevel: minor
# Replace instances with new AMI after platform update
# (not just patching in-place — a full rolling instance replacement)
InstanceRefreshEnabled: true
For MCP servers using the Docker platform, managed updates patch the Docker daemon and OS packages on the host EC2 instance, but do not update your container image — your MCP server image is pinned to the ECR image tag you specify in Dockerrun.aws.json. Manage application updates (Node.js version inside the container, npm dependencies) through your image build and ECR push pipeline.
Complete example: .ebextensions/app.config and secrets hook
The following is a complete production configuration for a Node.js MCP server combining enhanced health, CloudWatch Logs, Secrets Manager integration, and managed updates.
# .ebextensions/app.config — complete production configuration
option_settings:
# Application environment (non-secret config)
aws:elasticbeanstalk:application:environment:
NODE_ENV: production
MCP_LOG_LEVEL: info
MCP_SERVER_NAME: "my-mcp-server"
# Health check at /health endpoint
aws:elasticbeanstalk:application:
Application Healthcheck URL: /health
# Enhanced health with CloudWatch streaming
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
HealthStreamingEnabled: true
HealthCheckSuccessThreshold: Ok
# nginx proxy
aws:elasticbeanstalk:environment:proxy:
ProxyServer: nginx
GzipCompression: true
# CloudWatch Logs streaming
aws:elasticbeanstalk:cloudwatch:logs:
StreamLogs: true
RetentionInDays: 30
DeleteOnTerminate: false
aws:elasticbeanstalk:cloudwatch:logs:health:
HealthStreamingEnabled: true
RetentionInDays: 7
DeleteOnTerminate: false
# Instance profile
aws:autoscaling:launchtemplate:
IamInstanceProfile: aws-elasticbeanstalk-ec2-role
InstanceType: t3.medium
# Managed updates during Tuesday 3 AM UTC
aws:elasticbeanstalk:managedactions:
ManagedActionsEnabled: true
PreferredStartTime: "Tue:03:00"
aws:elasticbeanstalk:managedactions:platformupdate:
UpdateLevel: minor
InstanceRefreshEnabled: true
# nginx SSE configuration
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;
}
packages:
yum:
jq: []
#!/bin/bash
# .platform/hooks/predeploy/00-inject-secrets.sh
set -euo pipefail
REGION="${AWS_REGION:-us-east-1}"
SECRET_NAME="mcp-server/production"
SECRET_JSON=$(aws secretsmanager get-secret-value \
--region "${REGION}" \
--secret-id "${SECRET_NAME}" \
--query SecretString --output text)
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' "$(echo "${SECRET_JSON}" | jq -r '.anthropic_api_key')" >> "${ENV_FILE}"
printf 'DATABASE_URL=%s\n' "$(echo "${SECRET_JSON}" | jq -r '.database_url')" >> "${ENV_FILE}"
echo "Secrets injected from ${SECRET_NAME}"
Connect AliveMCP to monitor the production MCP server at https://mcp-server-prod.us-east-1.elasticbeanstalk.com/health and the green environment at https://mcp-server-green.us-east-1.elasticbeanstalk.com/health during the validation window before an eb swap. This gives you external confirmation that the green environment is healthy from the perspective of real network paths before you route production traffic to it.