How to Deploy a Full-Stack Application to AWS using EC2 and S3
How to Deploy a Full-Stack Application to AWS using EC2 and S3
This guide provides a professional workflow for hosting a dynamic backend on an EC2 instance while offloading static assets to S3 for optimal performance and scalability.
What You'll Need
- AWS Account with IAM permissions
- SSH Key Pair (.pem file)
- A production-ready full-stack application
- Domain name (optional, for custom DNS)
Steps
Step 1: Provision the EC2 Instance
Launch a T3.micro or T3.small instance using an Amazon Linux 2023 or Ubuntu AMI. Select a region closest to your target users and ensure you associate your SSH key pair for secure shell access.
Step 2: Configure Security Groups
Edit the instance security group to allow inbound traffic on port 22 for SSH, port 80 for HTTP, and port 443 for HTTPS. Restrict SSH access to your specific IP address to prevent unauthorized brute-force attempts.
Step 3: Set Up S3 for Static Assets
Create an S3 bucket and upload your frontend build folder (HTML, CSS, JS). Enable 'Static Website Hosting' in the bucket properties and update the bucket policy to allow public read access for the objects.
Step 4: Prepare the Backend Environment
SSH into your EC2 instance and install the necessary runtime environment, such as Node.js, Python, or Java. Clone your repository from Git and install dependencies using a production-specific flag to avoid installing development tools.
Step 5: Configure Environment Variables
Create a .env file on the server to store sensitive credentials, such as database strings and API keys. Ensure this file is excluded from version control and has restricted file permissions to protect secret data.
Step 6: Deploy a Process Manager
Install a process manager like PM2 or systemd to keep your application running in the background. This ensures the server automatically restarts the application if it crashes or if the instance reboots.
Step 7: Implement a Reverse Proxy
Install Nginx to act as a reverse proxy, routing external traffic from port 80 to your application's internal port. This improves security and allows you to handle SSL termination more efficiently.
Step 8: Connect Frontend to Backend
Update your frontend API configuration to point to the EC2 instance's Elastic IP or custom DNS. Deploy the updated build to the S3 bucket to establish the connection between the client and server.
Expert Tips
- Use an Elastic IP for your EC2 instance to prevent the public IP from changing after a reboot.
- Implement a CloudFront distribution in front of S3 to cache content globally and enable HTTPS.
- Regularly snapshot your EBS volumes to create reliable backup and recovery points.
See also
- Implementing a Scalable Authentication System in Python with FastAPI and JWT
- REST vs. GraphQL: Choosing the Right Architecture for Scalable APIs
- How to Optimize Complex SQL Database Queries for Performance
- Best Practices for Clean Code and Maintainability in JavaScript