How to Deploy to Aws Ec2

How to Deploy to AWS EC2 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 cl

Oct 30, 2025 - 12:12
Oct 30, 2025 - 12:12
 1

How to Deploy to AWS EC2

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 managed platforms that abstract away server details, EC2 gives you full administrative access to virtual machines, allowing you to customize every aspect of your deployment environment—from operating system and networking to security and performance tuning.

This guide walks you through the complete process of deploying an application to AWS EC2, from initial setup to production-ready configuration. We’ll cover not just the mechanics of launching an instance, but also how to secure it, automate deployments, monitor performance, and follow industry best practices. By the end of this tutorial, you’ll have a comprehensive understanding of how to deploy, manage, and maintain applications on EC2 with confidence and efficiency.

Step-by-Step Guide

1. Set Up an AWS Account

Before you can deploy to EC2, you need an active AWS account. If you don’t already have one, visit aws.amazon.com and click “Create an AWS Account.” You’ll be asked to provide basic personal or business information, a valid credit card (for billing purposes), and a phone number for verification.

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 at console.aws.amazon.com. This is your central hub for managing all AWS services, including EC2.

2. Understand EC2 Instance Types

EC2 offers a wide variety of instance types optimized for different workloads. Choosing the right one is critical for performance and cost-efficiency.

  • T instances (e.g., t3.micro, t3.small): Burstable performance, ideal for development, testing, and low-traffic websites.
  • M instances (e.g., m5.large): Balanced compute, memory, and networking; suitable for general-purpose applications.
  • C instances (e.g., c5.large): Compute-optimized for CPU-intensive tasks like batch processing and scientific modeling.
  • R instances (e.g., r5.large): Memory-optimized for in-memory databases and analytics workloads.
  • G instances: GPU-accelerated for machine learning, graphics rendering, and video encoding.

For beginners, start with a t3.micro or t3.small. These are cost-effective and provide enough resources to run a basic web server, API, or CMS like WordPress or Node.js.

3. Launch an EC2 Instance

To launch your first EC2 instance:

  1. In the AWS Console, navigate to the EC2 Dashboard.
  2. Click Launch Instance.
  3. Choose an Amazon Machine Image (AMI). For most use cases, select Amazon Linux 2 or Ubuntu Server 22.04 LTS. Both are free-tier eligible, well-documented, and widely supported.
  4. Select an instance type (e.g., t3.micro).
  5. Click Next: Configure Instance Details. Here, you can configure networking, IAM roles, and auto-recovery settings. For a basic deployment, leave defaults unless you have specific requirements.
  6. Click Next: Add Storage. The default 8 GB root volume is sufficient for testing. You can increase it to 20–30 GB if you plan to store logs, databases, or media files.
  7. Click Next: Add Tags. Tags help organize and identify your resources. Add a key-value pair like Name = MyWebServer.
  8. Click Next: Configure Security Group. This is critical. A security group acts as a virtual firewall. Create a new group or use an existing one. Add rules to allow:
    • SSH (port 22) from your IP address only (not 0.0.0.0/0) for secure remote access.
    • HTTP (port 80) from 0.0.0.0/0 to allow public web traffic.
    • HTTPS (port 443) from 0.0.0.0/0 if you plan to use SSL/TLS.

  9. Click Review and Launch. Review all settings, then click Launch.
  10. You’ll be prompted to select or create a key pair. This is your private key (.pem file) used to authenticate SSH connections. Download and store this file securely. You cannot recover it later. If you lose it, you’ll need to terminate the instance and start over.

After clicking “Launch,” your instance will enter the “pending” state. Within a few minutes, it will transition to “running.” You’ll see the instance ID (e.g., i-1234567890abcdef0) and public IP address.

4. Connect to Your EC2 Instance via SSH

Once your instance is running, you need to connect to it to install and configure your application.

On macOS or Linux, open a terminal and use the following command:

ssh -i /path/to/your-key-pair.pem ubuntu@your-public-ip-address

For Ubuntu AMIs, the default username is ubuntu. For Amazon Linux 2, use ec2-user.

On Windows, use PuTTY or Windows Terminal with OpenSSH. If using PuTTY, convert your .pem file to .ppk using PuTTYgen, then load it in the SSH authentication settings.

After successful login, you’ll see a command prompt. You’re now inside your EC2 instance.

5. Install a Web Server and Application Runtime

Now that you’re connected, install the necessary software stack. For this example, we’ll deploy a Node.js application.

Update the package manager:

sudo apt update && sudo apt upgrade -y

Install Node.js and npm:

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -

sudo apt install -y nodejs

node -v

npm -v

Install PM2 (a production process manager for Node.js):

sudo npm install -g pm2

6. Deploy Your Application Code

There are several ways to get your code onto the EC2 instance:

  • Git clone: Install Git and clone your repository directly from GitHub, GitLab, or Bitbucket.
  • SCP: Copy files from your local machine using Secure Copy.
  • SFTP: Use an SFTP client like FileZilla or WinSCP to transfer files.

For this example, we’ll use Git:

sudo apt install git -y

git clone https://github.com/yourusername/your-app.git

cd your-app

npm install

Ensure your application has a start script in package.json:

"scripts": {

"start": "node server.js"

}

Start your app with PM2:

pm2 start server.js --name "my-app"

Verify it’s running:

pm2 list

You should see your app listed with status “online.”

7. Configure a Reverse Proxy with Nginx

While Node.js can serve HTTP requests directly, it’s best practice to use a reverse proxy like Nginx for better performance, static file handling, and SSL termination.

Install Nginx:

sudo apt install nginx -y

Disable the default site and create a new config:

sudo rm /etc/nginx/sites-enabled/default

sudo nano /etc/nginx/sites-available/my-app

Add this configuration:

server {

listen 80;

server_name your-domain.com www.your-domain.com;

location / {

proxy_pass http://localhost:3000;

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;

}

}

Enable the site and test the config:

sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/

sudo nginx -t

sudo systemctl restart nginx

Now, when you visit your EC2 public IP address in a browser, you should see your application.

8. Set Up a Domain Name (Optional but Recommended)

To use a custom domain (e.g., www.yourapp.com), register a domain through a registrar like Namecheap or Google Domains, then point it to your EC2 public IP using an A record.

Alternatively, use Amazon Route 53 for DNS management. Create a hosted zone for your domain and add an A record pointing to your EC2 instance’s public IPv4 address.

Important: EC2 public IPs change when you stop and start instances. For production, assign an Elastic IP (static IP) from the EC2 Dashboard under “Elastic IPs.” Associate it with your instance.

9. Enable HTTPS with Let’s Encrypt

Modern web applications require HTTPS. Use Let’s Encrypt and Certbot to obtain a free SSL certificate.

Install Certbot:

sudo apt install certbot python3-certbot-nginx -y

Run Certbot:

sudo certbot --nginx -d your-domain.com -d www.your-domain.com

Follow the prompts. Certbot will automatically configure Nginx to use HTTPS and set up automatic renewal.

Test renewal:

sudo certbot renew --dry-run

Now your site is accessible via https://your-domain.com.

10. Automate Deployment with CI/CD (Optional Advanced Step)

Manually deploying via SSH is fine for development, but for production, automate deployments using CI/CD pipelines.

Use GitHub Actions, GitLab CI, or AWS CodeDeploy to automatically pull the latest code, install dependencies, restart services, and validate health on deployment.

Example GitHub Actions workflow (.github/workflows/deploy.yml):

name: Deploy to EC2

on:

push:

branches: [ main ]

jobs:

deploy:

runs-on: ubuntu-latest

steps:

- uses: actions/checkout@v3

- name: Deploy via SSH

uses: appleboy/ssh-action@v0.1.7

with:

host: ${{ secrets.EC2_HOST }}

username: ubuntu

key: ${{ secrets.EC2_KEY }}

script: |

cd /home/ubuntu/my-app

git pull origin main

npm install

pm2 restart my-app

Store your EC2 private key and public IP as GitHub Secrets for security.

Best Practices

1. Use IAM Roles Instead of Access Keys

Never hardcode AWS access keys into your application or scripts. Instead, assign an IAM role to your EC2 instance. This allows your application to securely access other AWS services (like S3, RDS, or DynamoDB) without credentials. IAM roles use temporary, rotating credentials managed automatically by AWS.

2. Apply the Principle of Least Privilege

Limit permissions for users, roles, and security groups. Only allow the minimum access required. For example, if your app only needs to read from an S3 bucket, don’t grant write or delete permissions.

3. Secure SSH Access

Disable password authentication and use key pairs only. Edit the SSH config:

sudo nano /etc/ssh/sshd_config

Ensure these lines are set:

PasswordAuthentication no

PermitRootLogin no

Restart SSH:

sudo systemctl restart sshd

Also, restrict SSH access to specific IP addresses in your security group instead of allowing 0.0.0.0/0.

4. Use Security Groups and Network ACLs

Security groups are stateful and apply at the instance level. Network ACLs are stateless and apply at the subnet level. Use both for defense-in-depth. Block all inbound traffic by default and open only necessary ports.

5. Monitor with CloudWatch

Enable detailed monitoring in EC2 to collect CPU, memory, disk, and network metrics. Set up CloudWatch Alarms to notify you of anomalies (e.g., CPU usage > 90% for 5 minutes). You can also install the CloudWatch Agent for custom metrics like memory usage and disk I/O.

6. Enable Automatic Backups

Use Amazon EBS Snapshots to back up your root volume and data volumes. Schedule daily snapshots using AWS Backup or Lambda + CloudWatch Events. Retain snapshots for at least 7–30 days depending on compliance needs.

7. Keep Software Updated

Regularly patch your OS and applications. Use automated tools like AWS Systems Manager Patch Manager to scan and update instances across your fleet.

8. Avoid Using Public IPs for Internal Communication

If multiple EC2 instances need to communicate (e.g., web server to database), use private IPs within the same VPC. This reduces latency, avoids public internet exposure, and saves data transfer costs.

9. Use Environment Variables for Secrets

Never store database passwords, API keys, or tokens in code. Use environment variables loaded at runtime. For Node.js, use a .env file with the dotenv package, or set them via systemd service files.

10. Plan for Scalability

EC2 is great for single instances, but for high availability, consider Auto Scaling Groups (ASG) behind an Application Load Balancer (ALB). ASG automatically replaces unhealthy instances and scales based on demand.

Tools and Resources

Essential AWS Tools

  • AWS CLI: Command-line interface for managing AWS services. Install via pip install awscli and configure with aws configure.
  • AWS Systems Manager: Centralized tool for patching, running commands, and managing configurations across EC2 instances.
  • CloudWatch: Monitoring and logging service for metrics, logs, and alarms.
  • EC2 Image Builder: Automate creation of customized AMIs with pre-installed software.
  • CodeDeploy: Automate application deployments to EC2 instances.

Third-Party Tools

  • Ansible: Configuration management tool to automate server setup and application deployment.
  • Docker: Containerize your app for consistent environments across development, staging, and production.
  • Terraform: Infrastructure-as-Code tool to define EC2 instances, VPCs, and security groups in declarative code.
  • GitHub Actions / GitLab CI: CI/CD pipelines to automate testing and deployment.
  • Netdata: Real-time performance monitoring dashboard for Linux systems.

Documentation and Learning Resources

Cost Optimization Tools

  • AWS Cost Explorer: Visualize and analyze your EC2 spending.
  • EC2 Instance Scheduler: Automatically start and stop instances based on time or schedule (ideal for dev/test environments).
  • Spot Instances: Use spare EC2 capacity at up to 90% discount for fault-tolerant workloads.
  • Reserved Instances: Commit to 1- or 3-year terms for significant savings on steady-state workloads.

Real Examples

Example 1: Deploying a React + Node.js Full-Stack App

A startup wants to deploy a full-stack application with a React frontend and a Node.js/Express backend API.

  • Backend: Runs on port 5000 using PM2.
  • Frontend: Built with npm run build and served as static files.
  • Nginx is configured to serve React files from /usr/share/nginx/html and proxy API requests to localhost:5000.
  • Let’s Encrypt SSL is enabled.
  • GitHub Actions triggers deployment on every push to main.

Result: The app is live at https://myapp.com with sub-second load times, secure HTTPS, and automated deployments.

Example 2: Running a WordPress Site on EC2

A small business wants to host a WordPress blog without using managed hosting.

  • EC2 instance: t3.micro, Ubuntu 22.04
  • LAMP stack installed: Apache, MySQL, PHP
  • WordPress downloaded and configured
  • RDS (Amazon Relational Database Service) used for MySQL to separate database from compute
  • CloudFront CDN for static assets
  • Automated daily EBS snapshots

Result: Faster performance than shared hosting, full control over plugins and themes, and scalability for traffic spikes.

Example 3: Microservices Architecture on EC2

An enterprise deploys three microservices: user service, order service, and payment service—all on separate EC2 instances within a private VPC.

  • Each service runs in a Docker container.
  • Internal communication uses private IPs and AWS Security Groups.
  • Application Load Balancer routes traffic based on path (e.g., /users → user service).
  • CloudWatch Logs aggregated from all instances.
  • Auto Scaling enabled for order service during peak hours.

Result: High availability, fault isolation, and cost-efficient scaling across services.

FAQs

Is EC2 the right choice for deploying my app?

EC2 is ideal if you need full control over your server environment, want to customize software stacks, or run legacy applications. If you prefer less operational overhead, consider AWS Elastic Beanstalk, Lambda, or ECS.

How much does EC2 cost?

Costs vary by instance type, region, and usage. A t3.micro costs about $0.0116 per hour (~$8.50/month) on-demand. With Reserved Instances or Spot Instances, you can reduce this by 40–90%. Use the AWS Pricing Calculator to estimate costs.

Can I use EC2 for production websites?

Absolutely. Many Fortune 500 companies run mission-critical applications on EC2. With proper architecture—load balancing, auto scaling, backups, and monitoring—EC2 is enterprise-ready.

What happens if my EC2 instance crashes?

EC2 instances are ephemeral. If the underlying hardware fails, AWS automatically restarts the instance on new hardware. However, data on the root volume is lost unless you use EBS volumes (which persist) or external storage like S3.

How do I update my app without downtime?

Use rolling deployments with Auto Scaling Groups or blue/green deployments. Alternatively, use a reverse proxy like Nginx to redirect traffic while restarting your app process.

Do I need a domain name to use EC2?

No. You can access your app via the public IP address. However, a domain name is essential for professional branding, SEO, and HTTPS certificates.

Can I run a database on EC2?

You can, but AWS recommends using RDS for managed databases. RDS handles backups, patching, replication, and scaling automatically. Running MySQL or PostgreSQL on EC2 requires manual administration.

How do I back up my EC2 instance?

Create EBS snapshots of your volumes. You can automate this using AWS Backup or custom scripts with the AWS CLI. Snapshots are incremental and stored in S3.

What’s the difference between EC2 and S3?

EC2 is for running applications and servers. S3 is for object storage—uploading files, images, videos, or backups. Use both together: store assets in S3 and serve them via your EC2 app.

Is EC2 secure by default?

No. Security is your responsibility under the Shared Responsibility Model. AWS secures the infrastructure; you secure the OS, applications, network, and data.

Conclusion

Deploying to AWS EC2 is a powerful skill that gives you unparalleled control over your application’s environment. From launching a simple web server to architecting complex microservices, EC2 serves as the foundation for countless cloud-native applications. This guide has walked you through every critical step—from creating your first instance and securing SSH access, to deploying applications, enabling HTTPS, and automating workflows with CI/CD.

Remember, the key to success with EC2 lies not just in technical execution but in following best practices: secure configurations, automated backups, monitoring, and continuous improvement. As you grow, consider evolving from single instances to Auto Scaling Groups, containerized deployments with ECS or EKS, and infrastructure-as-code with Terraform.

EC2 is not just a virtual machine—it’s a platform for innovation. Whether you’re building your first website or scaling a global SaaS product, mastering EC2 deployment is a foundational step toward cloud proficiency. Start small, learn incrementally, and always prioritize security and reliability. With the tools and knowledge outlined here, you’re now equipped to deploy confidently, operate efficiently, and scale intelligently on AWS EC2.