How to Deploy to Aws Ec2
How to Deploy to AWS EC2: A Complete Step-by-Step Guide Deploying applications to Amazon Web Services (AWS) Elastic Compute Cloud (EC2) is one of the most fundamental and widely adopted practices in modern cloud infrastructure. Whether you're a startup launching your first web app or an enterprise scaling complex microservices, EC2 provides the flexibility, scalability, and control needed to run v
How to Deploy to AWS EC2: A Complete Step-by-Step Guide
Deploying applications to Amazon Web Services (AWS) Elastic Compute Cloud (EC2) is one of the most fundamental and widely adopted practices in modern cloud infrastructure. Whether you're a startup launching your first web app or an enterprise scaling complex microservices, EC2 provides the flexibility, scalability, and control needed to run virtually any workload in the cloud. Unlike platform-as-a-service (PaaS) solutions that abstract away infrastructure, EC2 gives you full administrative access to virtual serversmaking it ideal for custom configurations, legacy applications, and performance-sensitive workloads.
This guide walks you through every critical step required to successfully deploy an application to AWS EC2. From setting up your AWS account and launching your first instance to configuring security, deploying code, and optimizing performance, youll learn not just how to deploybut how to deploy securely, efficiently, and at scale. By the end of this tutorial, youll have a production-ready deployment pipeline that can be replicated across environments and integrated into automated workflows.
Step-by-Step Guide
Step 1: Set Up an AWS Account
Before deploying to EC2, you need an active AWS account. If you dont already have one, visit aws.amazon.com and click Create an AWS Account. Follow the prompts to enter your personal or business information, payment details, and verify your identity via phone or text.
AWS offers a Free Tier for new users, which includes 750 hours per month of t2.micro or t3.micro instance usage for one year. This is sufficient for learning, testing, and small-scale deployments. Be sure to monitor your usage to avoid unexpected charges once the free tier expires.
After signing up, log in to the AWS Management Console. Familiarize yourself with the dashboard. The console provides access to all AWS services, but for this guide, well focus primarily on EC2, IAM, and VPC.
Step 2: Understand EC2 Instance Types and Regions
EC2 offers a wide variety of instance types optimized for different workloads. The most common categories include:
- T-series (Burstable Performance): Ideal for development, testing, and low-traffic websites. Examples: t3.micro, t3.small.
- M-series (General Purpose): Balanced compute, memory, and networking. Good for web servers, application servers.
- C-series (Compute Optimized): High-performance processors for batch processing, gaming servers.
- R-series (Memory Optimized): Large amounts of RAM for in-memory databases like Redis or SAP HANA.
- G-series (GPU Optimized): For machine learning, graphics rendering, and scientific simulations.
For beginners, start with a t3.micro or t3.small instance. These are cost-effective and provide enough resources to run a basic Node.js, Python, or PHP application.
Also choose an AWS region close to your target audience. Regions like us-east-1 (N. Virginia), us-west-2 (Oregon), and eu-west-1 (Ireland) are popular due to their reliability and low latency. You can switch regions using the dropdown menu in the top-right corner of the AWS console.
Step 3: Configure Security Groups
Security Groups act as virtual firewalls for your EC2 instances. They control inbound and outbound traffic at the instance level. Always follow the principle of least privilegeonly open ports that are absolutely necessary.
To create a Security Group:
- In the AWS Console, navigate to EC2 > Security Groups.
- Click Create Security Group.
- Enter a name (e.g., web-server-sg) and description.
- Under Inbound Rules, add the following:
- Type: HTTP, Source: 0.0.0.0/0 (or restrict to your IP for production)
- Type: SSH, Source: Your IP address (e.g., 203.0.113.1/32)
- Type: HTTPS, Source: 0.0.0.0/0 (if serving over SSL)
Never open SSH (port 22) to the entire internet (0.0.0.0/0) in production. Use a static IP or AWS Session Manager for secure access without exposing SSH publicly.
Step 4: Launch an EC2 Instance
Now, launch your first EC2 instance:
- In the AWS Console, go to EC2 > Instances > Launch Instance.
- Choose an Amazon Machine Image (AMI). For most applications, select Amazon Linux 2 or Ubuntu Server 22.04 LTS. These are well-supported, secure, and come with package managers preinstalled.
- Select an instance type (e.g., t3.micro).
- Click Next: Configure Instance Details. Leave defaults unless you need advanced networking (e.g., multiple NICs, dedicated hosts).
- On the Add Storage page, increase the root volume size to at least 20 GB if you plan to install databases or store logs. SSD (gp3) is recommended for performance.
- Click Add Tags. Add a key-value pair: Key: Name, Value: MyWebAppServer. This helps identify instances later.
- Under Configure Security Group, select Choose an existing security group and pick the one you created earlier.
- Click Review and Launch. Verify all settings, then click Launch.
Youll be prompted to select or create a key pair. This is your private key used to SSH into the instance.
- If you have an existing key pair, select it.
- If not, click Create a new key pair, give it a name (e.g., my-key-pair), and download the .pem file.
Important: Store this .pem file securely. It cannot be recovered if lost. Never commit it to version control. Set permissions: chmod 400 my-key-pair.pem.
Step 5: Connect to Your EC2 Instance via SSH
Once your instance is running (status = running), connect to it using SSH.
On macOS or Linux, open your terminal and run:
ssh -i "my-key-pair.pem" ec2-user@your-instance-public-ip
For Ubuntu AMIs, use ubuntu@ instead of ec2-user@:
ssh -i "my-key-pair.pem" ubuntu@your-instance-public-ip
On Windows, use PuTTY or Windows Terminal with OpenSSH. Convert your .pem file to .ppk using PuTTYgen if using PuTTY.
Once connected, update your system:
sudo yum update -y Amazon Linux 2
OR
sudo apt update && sudo apt upgrade -y Ubuntu
Step 6: Install Required Software
Now install the software stack your application requires. For example, to deploy a Node.js app:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v
npm -v
For a Python Flask app:
sudo apt install python3-pip python3-venv -y
python3 -m venv myapp-env
source myapp-env/bin/activate
pip install flask gunicorn
For a PHP application with Apache:
sudo yum install httpd php php-mysql -y Amazon Linux
OR
sudo apt install apache2 php libapache2-mod-php -y Ubuntu
sudo systemctl start httpd
sudo systemctl enable httpd
Step 7: Deploy Your Application Code
There are multiple ways to deploy code to EC2. Well cover two common methods:
Method A: Upload via SCP
If you have a local project folder, use SCP to transfer it:
scp -i "my-key-pair.pem" -r ./my-app ec2-user@your-instance-public-ip:/home/ec2-user/
Method B: Clone from Git
Install Git and clone your repository directly on the instance:
sudo yum install git -y Amazon Linux
OR
sudo apt install git -y Ubuntu
git clone https://github.com/yourusername/your-repo.git
cd your-repo
Install dependencies:
npm install Node.js
pip install -r requirements.txt Python
composer install PHP
Step 8: Configure a Process Manager (PM2, Gunicorn, Supervisor)
Running apps directly via node app.js or python app.py is not suitable for production. If the terminal closes, the app stops. Use a process manager to keep your app running.
For Node.js: Use PM2
npm install -g pm2
pm2 start app.js --name "my-app"
pm2 startup
pm2 save
PM2 will automatically restart your app on boot and manage logs.
For Python: Use Gunicorn + Nginx
gunicorn --bind 0.0.0.0:8000 --workers 3 app:app
Install Nginx as a reverse proxy:
sudo apt install nginx -y
sudo nano /etc/nginx/sites-available/myapp
Add this configuration:
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Enable the site:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
Step 9: Set Up a Domain Name and SSL Certificate
Point a domain to your EC2 instance using an A record in your DNS provider (e.g., Route 53, Cloudflare, GoDaddy). Use your instances public IPv4 address.
To secure your site with HTTPS, obtain a free SSL certificate from Lets Encrypt using Certbot:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Certbot will automatically configure Nginx to use HTTPS and set up automatic renewal.
Step 10: Test and Monitor Your Deployment
Visit your domain in a browser. If you see your application, congratulationsyouve successfully deployed to EC2!
Monitor performance using AWS CloudWatch:
- Go to CloudWatch > Metrics > EC2.
- View CPU utilization, network in/out, disk read/write.
- Create alarms for thresholds (e.g., CPU > 80% for 5 minutes).
Check logs:
pm2 logs Node.js
sudo tail -f /var/log/nginx/access.log Nginx
sudo tail -f /var/log/nginx/error.log
Best Practices
Use IAM Roles Instead of Access Keys
Never store AWS access keys on EC2 instances. Instead, assign an IAM role to your instance. This allows your application to securely access other AWS services (like S3, RDS, or DynamoDB) without hardcoded credentials.
To assign a role:
- Create an IAM policy with necessary permissions (e.g., read-only access to S3).
- Create an IAM role of type EC2 and attach the policy.
- When launching the instance, select the role under IAM instance profile.
Enable Auto-Scaling and Load Balancing
As your application grows, a single EC2 instance becomes a bottleneck. Use an Application Load Balancer (ALB) to distribute traffic across multiple instances.
Combine this with an Auto Scaling Group that automatically adds or removes instances based on CPU usage or request volume. This improves availability and reduces downtime during traffic spikes.
Use EBS Snapshots for Backups
Regularly create snapshots of your EBS volumes. Snapshots are incremental and stored in S3, making them cost-effective and reliable for disaster recovery.
Set up automated snapshots using AWS Backup or cron jobs with the AWS CLI:
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description "Daily backup"
Keep Software Updated
Regularly patch your OS and applications. Use automated tools like AWS Systems Manager Patch Manager to schedule and apply updates across multiple instances.
Implement Infrastructure as Code (IaC)
Manually configuring EC2 instances is error-prone and unrepeatable. Use tools like Terraform or AWS CloudFormation to define your infrastructure in code.
Example Terraform snippet:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
key_name = "my-key-pair"
security_groups = ["web-server-sg"]
tags = {
Name = "MyWebAppServer"
}
}
With IaC, you can version control, test, and deploy identical environments across staging, QA, and production.
Disable Root Login and Use SSH Keys Only
Ensure SSH access is restricted to key-based authentication only:
sudo nano /etc/ssh/sshd_config
Set:
PermitRootLogin no
PasswordAuthentication no
Then restart SSH:
sudo systemctl restart sshd
Log Centralization and Monitoring
Use AWS CloudWatch Logs or third-party tools like Datadog or Loki to centralize logs from multiple instances. This helps with debugging, compliance, and auditing.
Install the CloudWatch agent:
sudo yum install -y amazon-cloudwatch-agent
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
Tools and Resources
Essential AWS Tools
- AWS CLI: Command-line interface for managing AWS services. Install with:
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" - AWS Systems Manager: Manage and monitor instances without SSH. Use Session Manager for secure, browser-based access.
- CodeDeploy: Automate application deployments to EC2. Integrates with CodePipeline and GitHub.
- CloudWatch: Monitoring, logging, and alerting. Essential for performance tracking.
- Route 53: AWSs DNS service. Use for domain registration and routing traffic to EC2.
Third-Party Tools
- Terraform: Open-source IaC tool for provisioning AWS resources across multiple clouds.
- Docker: Containerize your app for consistency across environments. Deploy containers on EC2 using ECS or Docker Compose.
- GitHub Actions / GitLab CI: Automate testing and deployment on code push.
- Ansible / Chef / Puppet: Configuration management tools to automate software setup.
- Netdata: Real-time performance monitoring dashboard for EC2 instances.
Learning Resources
- AWS EC2 Documentation
- AWS Hands-On Tutorial: Deploy a Web App
- Udemy: AWS Certified Solutions Architect
- AWS GitHub Organization Open-source tools and examples
Real Examples
Example 1: Deploying a React Frontend with Node.js Backend
A startup wants to deploy a full-stack application: a React frontend served by an Express backend.
- Build React app:
npm run build? generates static files in/build. - On EC2: Install Node.js and Nginx.
- Copy
/buildfolder to/var/www/html. - Start Express server on port 3001 using PM2.
- Configure Nginx to serve static files and proxy API requests:
server {
listen 80;
server_name app.example.com;
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
SSL is added via Certbot. The app now serves securely over HTTPS with zero downtime.
Example 2: Deploying a Django App with PostgreSQL on EC2
A data analytics company deploys a Django application with a PostgreSQL database.
- EC2 instance: Ubuntu 22.04, t3.medium.
- Install PostgreSQL:
sudo apt install postgresql postgresql-contrib - Create database and user:
sudo -u postgres psql - Install Python 3.10, virtualenv, Gunicorn, Nginx.
- Clone Git repo, install requirements, run migrations.
- Configure Gunicorn to run as a service using systemd.
- Set up Nginx to proxy to Gunicorn on port 8000.
- Use AWS RDS for PostgreSQL instead of local DB for better reliability and backups.
Result: A scalable, secure, and monitored Django application serving 50K+ monthly users.
Example 3: Multi-Tier Architecture with Auto Scaling
An e-commerce platform uses:
- Application tier: Auto Scaling Group of t3.small EC2 instances behind an ALB.
- Database tier: Amazon RDS (PostgreSQL) with Multi-AZ for failover.
- Cache tier: ElastiCache (Redis) for session storage.
- Storage: S3 for product images.
- CI/CD: GitHub Actions triggers CodeDeploy on merge to main branch.
This architecture handles Black Friday traffic spikes automatically and recovers from instance failures without manual intervention.
FAQs
Can I deploy to EC2 for free?
Yes, AWS Free Tier includes 750 hours/month of t2.micro or t3.micro instances for 12 months. You can host a personal blog, portfolio, or small API without cost during this period. After the free tier, costs are minimalaround $5$10/month for a single small instance.
Is EC2 better than Heroku or Vercel?
EC2 gives you full control over the server environment, which is essential for custom software, legacy systems, or compliance requirements. Heroku and Vercel are easier to use but abstract away infrastructure, limiting customization. Choose EC2 if you need root access, specific OS versions, or advanced networking.
How do I update my app without downtime?
Use a blue-green deployment strategy. Launch a new EC2 instance with the updated code, test it, then route traffic to it using a load balancer. Once confirmed, terminate the old instance. Tools like CodeDeploy automate this process.
What happens if my EC2 instance crashes?
EC2 instances are ephemeral. If an instance fails, it must be replaced. To ensure reliability, use Auto Scaling Groups and Elastic Load Balancers. Always store data on persistent volumes (EBS) or external services (RDS, S3).
How do I secure my EC2 instance?
Follow these steps:
- Use SSH key pairs only, disable password login.
- Restrict Security Groups to minimal ports and IPs.
- Keep software updated.
- Use IAM roles instead of access keys.
- Enable CloudWatch Logs and set up alarms.
- Regularly audit with AWS Trusted Advisor.
Can I use EC2 for machine learning models?
Absolutely. Use GPU instances like p3.2xlarge or g4dn.xlarge to train and serve models. Install CUDA, TensorFlow, or PyTorch, and expose your model via a REST API using Flask or FastAPI. Combine with SageMaker for managed ML workflows.
How much does EC2 cost per month?
Costs vary by instance type, region, and usage:
- t3.micro: ~$4.50/month
- t3.small: ~$9.00/month
- t3.medium: ~$18.00/month
- c5.large: ~$45.00/month
- p3.2xlarge: ~$300+/month
Use the AWS Pricing Calculator to estimate costs based on your specific needs.
Do I need a domain name to deploy on EC2?
No. You can access your app via the public IP address (e.g., http://54.123.45.67). However, for production use, a domain name improves professionalism, SEO, and enables HTTPS via SSL certificates.
Conclusion
Deploying to AWS EC2 is a powerful skill that opens the door to full control over your applications infrastructure. While it requires more setup than managed platforms, the flexibility, scalability, and cost-efficiency make it indispensable for developers, startups, and enterprises alike.
This guide has walked you through every critical phasefrom creating your first EC2 instance and securing it with SSH and IAM roles, to deploying code, configuring web servers, adding SSL, and implementing monitoring and automation. Youve seen real-world examples of how businesses use EC2 to run everything from static websites to high-traffic microservices.
Remember: deployment is not a one-time task. Its an ongoing process of optimization, security hardening, and scaling. Use Infrastructure as Code to make deployments repeatable. Automate updates and backups. Monitor performance continuously. And always test changes in a staging environment before pushing to production.
As cloud technologies evolve, EC2 remains a foundational pillar of AWSand a cornerstone of modern DevOps. Mastering it positions you not just to deploy applications, but to architect resilient, scalable, and secure systems that can grow with your business.
Now that you know how to deploy to AWS EC2, the next step is to automate it. Explore AWS CodeDeploy, GitHub Actions, or Terraform to turn your manual process into a seamless, repeatable pipeline. The cloud is waitingdeploy confidently.