Админка
please wait

AWS Elastic Beanstalk provides a managed platform for deploying web applications without managing the underlying infrastructure. It handles capacity provisioning, load balancing, auto-scaling, and application health monitoring. This guide covers deploying containerized applications to Elastic Beanstalk from a senior developer's perspective.

Why Elastic Beanstalk

Elastic Beanstalk offers several advantages:

  1. Managed Infrastructure: AWS handles servers, load balancers, and scaling
  2. Docker Support: Deploy containers without Kubernetes complexity
  3. Easy Rollbacks: One-click rollback to previous versions
  4. Integrated Monitoring: CloudWatch metrics out of the box
  5. Cost-Effective: Pay only for underlying AWS resources

Initial Setup

Create Elastic Beanstalk Application

  1. Go to the AWS Management Console
  2. Search for "Elastic Beanstalk" in Find Services
  3. Click "Create Application"
  4. Enter an application name (e.g., "my-docker-app")
  5. Select "Docker" as the platform
  6. Choose "Docker running on 64-bit Amazon Linux 2"
  7. Click "Create Application"

Wait for environment creation (green checkmark indicates success).

Configure Instance Type

The default t2.micro instance often times out during builds. Upgrade to t2.small:

  1. In the left sidebar, click "Configuration"
  2. Find "Capacity" and click "Edit"
  3. Change "Instance Type" from t2.micro to t2.small
  4. Click "Apply"

Note: t2.small is outside the free tier but prevents build failures.

Docker Configuration

Single Container Deployment

Create Dockerfile in your project root:

# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Production stage
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Multi-Container with Docker Compose

Create docker-compose.yml for Elastic Beanstalk:

version: '3.8'
services:
nginx:
build:
context: ./nginx
dockerfile: Dockerfile
ports:
- "80:80"
depends_on:
- api
- frontend
api:
build:
context: ./api
dockerfile: Dockerfile
environment:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
- REDIS_HOST=redis
depends_on:
- redis
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
environment:
- API_URL=http://api:5000
redis:
image: redis:alpine
worker:
build:
context: ./worker
dockerfile: Dockerfile
environment:
- REDIS_HOST=redis

Create nginx/default.conf:

upstream frontend {
server frontend:3000;
}
upstream api {
server api:5000;
}
server {
listen 80;
location / {
proxy_pass http://frontend;
}
location /sockjs-node {
proxy_pass http://frontend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://api;
}
}

CI/CD with Travis CI

IAM User Setup

Create deployment credentials:

  1. Search for "IAM" in the AWS Console
  2. Click "Users" → "Add User"
  3. Enter username: "eb-deploy-user"
  4. Select "Programmatic Access"
  5. Click "Attach Existing Policies Directly"
  6. Search and select "AWSElasticBeanstalkFullAccess"
  7. Complete creation and save the Access Key ID and secret

Travis Configuration

Add AWS credentials to Travis:

  1. Go to your Travis Dashboard
  2. Click repository → "More Options" → "Settings"
  3. Add environment variables:

- AWSACCESSKEY: Your IAM access key - AWSSECRETKEY: Your IAM secret key

Create .travis.yml:

language: generic
services:
- docker
before_install:
- docker build -t my-app-test -f Dockerfile.dev .
script:
- docker run -e CI=true my-app-test npm test -- --coverage
deploy:
provider: elasticbeanstalk
region: us-east-1
app: my-docker-app
env: my-docker-app-env
bucket_name: elasticbeanstalk-us-east-1-123456789012
bucket_path: my-docker-app
on:
branch: main
access_key_id: $AWS_ACCESS_KEY
secret_access_key: $AWS_SECRET_KEY

Find your bucket name:

  1. Go to S3 in the AWS Console
  2. Look for a bucket starting with "elasticbeanstalk-" matching your region
  3. Copy the full bucket name

Database Configuration with RDS

Create RDS Instance

  1. Search for "RDS" in the AWS Console
  2. Click "Create Database"
  3. Select "PostgreSQL" (or MySQL)
  4. Choose the "Free tier" template for testing
  5. Configure:

- DB instance identifier: my-app-db - Master username: admin - Master password: (secure password) 6. Under "Connectivity": - Choose your VPC - Create a new security group: my-app-db-sg 7. Click "Create Database"

Configure Security Groups

Allow Elastic Beanstalk to access RDS:

  1. Go to EC2 → Security Groups
  2. Find your RDS security group
  3. Edit inbound rules
  4. Add rule:

- Type: PostgreSQL (port 5432) - Source: Security group of your EB environment 5. Save rules

Set Environment Variables

  1. Go to Elastic Beanstalk → Configuration
  2. Find "Software" and click "Edit"
  3. Under "Environment properties," add:

- DATABASEURL: postgres://admin:password@hostname:5432/myapp - RAILSENV: production - SECRETKEYBASE: (generate with rails secret) 4. Click "Apply"

Redis with ElastiCache

Create Redis Cluster

  1. Search for "ElastiCache" in the AWS Console
  2. Click "Create" under Redis
  3. Configure:

- Name: my-app-redis - Node type: cache.t3.micro - Number of replicas: 0 (for development) 4. Select your VPC and subnet group 5. Create a new security group 6. Click "Create"

Configure Security

  1. Edit the ElastiCache security group
  2. Add inbound rule:

- Type: Custom TCP (port 6379) - Source: EB environment security group 3. Add an environment variable in EB: - REDIS_HOST: (ElastiCache endpoint without port)

Health Checks and Monitoring

Configure Health Check

Create .ebextensions/healthcheck.config:

option_settings:
aws:elasticbeanstalk:application:
Application Healthcheck URL: /health
aws:elasticbeanstalk:environment:process:default:
HealthCheckPath: /health
HealthCheckInterval: 30
HealthCheckTimeout: 5
HealthyThresholdCount: 3
UnhealthyThresholdCount: 5

Implement a health endpoint in your app:

// Express.js example
app.get('/health', (req, res) => {
// Check database connection
db.query('SELECT 1')
.then(() => {
res.status(200).json({ status: 'healthy' });
})
.catch(() => {
res.status(503).json({ status: 'unhealthy' });
});
});

CloudWatch Alarms

Create .ebextensions/cloudwatch.config:

Resources:
CPUAlarmHigh:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: "CPU > 80% for 5 minutes"
MetricName: CPUUtilization
Namespace: AWS/EC2
Statistic: Average
Period: 300
EvaluationPeriods: 1
Threshold: 80
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref NotificationTopic
NotificationTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint: [email protected]
Protocol: email

Auto Scaling Configuration

Create .ebextensions/autoscaling.config:

option_settings:
aws:autoscaling:asg:
MinSize: 2
MaxSize: 10
aws:autoscaling:trigger:
MeasureName: CPUUtilization
Statistic: Average
Unit: Percent
LowerThreshold: 30
UpperThreshold: 70
LowerBreachScaleIncrement: -1
UpperBreachScaleIncrement: 1
aws:elasticbeanstalk:environment:
LoadBalancerType: application

HTTPS Configuration

Request SSL Certificate

  1. Go to AWS Certificate Manager (ACM)
  2. Click "Request Certificate"
  3. Enter domain: *.example.com
  4. Validate via DNS or email
  5. Wait for the certificate to be issued

Configure HTTPS

Create .ebextensions/https.config:

option_settings:
aws:elb:listener:443:
ListenerProtocol: HTTPS
InstanceProtocol: HTTP
InstancePort: 80
SSLCertificateId: arn:aws:acm:region:account:certificate/id
aws:elb:listener:80:
ListenerEnabled: false

Deployment Best Practices

Blue-Green Deployments

For zero-downtime deployments:

  1. Create a new environment (clone existing)
  2. Deploy new version to new environment
  3. Test thoroughly
  4. Swap environment URLs in the EB console
  5. Terminate old environment after verification

Rolling Updates

Configure in .ebextensions/deployment.config:

option_settings:
aws:elasticbeanstalk:command:
DeploymentPolicy: Rolling
BatchSizeType: Percentage
BatchSize: 25

Troubleshooting

View Logs

# Using the EB CLI
eb logs
# Or in the AWS Console:
# Elastic Beanstalk → Logs → Request Logs

Common Issues

Build timeout: Increase instance size to t2.small or larger

Container fails to start: Check Docker logs:

eb ssh
docker logs $(docker ps -q)

Database connection refused: Verify security group rules allow traffic from EB to RDS

502 Bad Gateway: Application crashed or not listening on the correct port

Key Takeaways

  1. Use Docker: Containerize for consistent deployments
  2. Separate concerns: Database and cache in managed services
  3. Security groups matter: Configure carefully for service communication
  4. Environment variables: Never hardcode credentials
  5. Monitor actively: Set up CloudWatch alarms from day one
  6. Plan for scaling: Configure auto-scaling before you need it

Elastic Beanstalk provides an excellent balance between infrastructure abstraction and control, making it ideal for teams that want managed deployments without full Kubernetes complexity.

 
 
 
Языки
Темы
Copyright © 1999 — 2026
ZK Interactive