Imagine launching a web server in the cloud. For most beginners, it's a monumental task, but with the right tools, we can simplify the process while still learning the ropes of AWS, Apache, SSL, and CloudFormation.
In this journey, I'll guide you through setting up a web server on AWS EC2, installing Apache, securing the connection with SSL certificates, and automating the process using CloudFormation. Along the way, you'll see both the manual and automated approaches — the "manual" approach lets us learn every step thoroughly, while the "automated" approach saves us time and headaches in the future.
What You'll Learn:
Let's start with a manual configuration, then use AWS CloudFormation to replicate the setup automatically. We'll finish by connecting our custom domain and securing the server with Let's Encrypt SSL.
Before diving into automation, we'll first manually configure the server. Think of this step as the "DIY" phase. While automation can save time, it's important to understand the fundamental steps that go into setting up the server.
AWS EC2 (Elastic Compute Cloud) is the heart of cloud computing. It provides scalable compute capacity, and you can think of it as your virtual machine in the cloud. For our project, we're using a t2.micro instance — a great choice for learning and small applications, especially since it falls under the AWS Free Tier.
Why EC2?
AWS EC2 is widely used for its flexibility and scalability. You can easily resize instances as your needs grow. Whether you're building a small app or a full enterprise infrastructure, EC2 has you covered.
EC2 Instance Types:
| Instance Type | vCPUs | Memory | Use Case | Free Tier Eligible |
|---|---|---|---|---|
| t2.micro | 1 | 1 GB | Low traffic websites, development | Yes |
| t2.small | 1 | 2 GB | Small databases, web servers | No |
| t3.medium | 2 | 4 GB | Medium traffic applications | No |
| m5.large | 2 | 8 GB | Production workloads | No |
The following diagram illustrates the complete AWS EC2 web server architecture, including security groups, networking, and SSL certificate management.
Set up a Security Group that allows traffic on:
Security Group Rules:
| Type | Protocol | Port Range | Source | Description |
|---|---|---|---|---|
| SSH | TCP | 22 | 0.0.0.0/0 | SSH access (restrict to your IP in production) |
| HTTP | TCP | 80 | 0.0.0.0/0 | HTTP web traffic |
| HTTPS | TCP | 443 | 0.0.0.0/0 | HTTPS secure web traffic |
| Custom TCP | TCP | 10000 | 0.0.0.0/0 | Webmin management interface |
Important Security Note: In production environments, restrict SSH (port 22) to your specific IP address or IP range. Allowing 0.0.0.0/0 (all IPs) is convenient for learning but creates security risks.
Create or select an existing key pair:
Review and launch the instance
Once the instance is running, it's time to SSH into it. Think of SSH as your secure tunnel to your remote server. By connecting via SSH, you can issue commands and configure the server as if you were sitting in front of it.
On Linux/macOS:
chmod 400 Test_key_Pair.pem
ssh -i Test_key_Pair.pem ubuntu@your-ec2-public-ip
On Windows (using PuTTY):
SSH Connection Command Breakdown:
chmod 400: Sets correct permissions on the private key (read-only for owner)-i Test_key_Pair.pem: Specifies the identity file (private key)ubuntu@your-ec2-public-ip: Username and EC2 instance public IP addressUpon Successful Connection:
Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 6.2.0-1009-aws x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
ubuntu@ip-172-31-xx-xx:~$
Here, the Test_key_Pair.pem is your SSH key that AWS provided. You'll need it to access your instance securely. Don't lose it!
Apache is one of the most popular open-source web servers. It's easy to configure, well-documented, and robust enough for most web applications.
Let's install Apache, enable it, and start it:
sudo apt update
sudo apt install -y apache2
sudo systemctl enable apache2
sudo systemctl start apache2
Command Explanation:
sudo apt update: Updates package lists from repositoriessudo apt install -y apache2: Installs Apache web server (the -y flag auto-confirms)sudo systemctl enable apache2: Configures Apache to start automatically on bootsudo systemctl start apache2: Starts the Apache service immediatelyCheck that Apache is running:
sudo systemctl status apache2
Expected Output:
● apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2024-01-15 10:30:25 UTC; 5min ago
Navigate to your EC2 instance's public IP address in a web browser:
http://your-ec2-public-ip
You should see the default Apache welcome page.
Now, Apache is up and running! Let's replace the default Apache landing page with something more personalized.
echo "<h1>🚀 CloudFormation Web Server</h1><p>This page was deployed automatically via CloudFormation.</p>" > /var/www/html/index.html
Reload the page in your browser to see your custom content.
Why Apache?
Apache is a classic choice for web hosting. While there are newer web servers (like Nginx), Apache remains a solid, reliable option for hosting websites, making it a great tool for this lab.
| Directory | Purpose |
|---|---|
| /var/www/html/ | Default document root (web content location) |
| /etc/apache2/ | Apache configuration files |
| /etc/apache2/sites-available/ | Available site configurations |
| /etc/apache2/sites-enabled/ | Enabled site configurations |
| /var/log/apache2/ | Apache log files (access.log, error.log) |
We need to ensure our website is secure. SSL certificates encrypt the data between the server and the client, which is crucial for user privacy and trust.
To get an SSL certificate for free, we'll use Let's Encrypt, a non-profit that provides free certificates.
First, we install Certbot, a tool for obtaining and managing Let's Encrypt certificates:
sudo apt install -y certbot python3-certbot-apache
Certbot Components:
certbot: Core certificate management toolpython3-certbot-apache: Apache plugin for automatic configurationNow, let's request an SSL certificate for our domain:
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
Command Parameters:
--apache: Use Apache plugin for automatic configuration-d yourdomain.com: Primary domain-d www.yourdomain.com: Additional subdomain (optional)Interactive Prompts:
Certbot automatically configures Apache to use SSL. It's as simple as that!
Certbot Actions:
Test your SSL configuration:
sudo apachectl configtest
sudo systemctl reload apache2
Visit your site using HTTPS:
https://yourdomain.com
You should see a padlock icon in the browser address bar, indicating a secure connection.
Why Let's Encrypt?
Let's Encrypt is a game-changer for website security. It provides free SSL certificates and automates the installation and renewal process. This has become a best practice in the industry.
SSL Certificate Details:
| Property | Value |
|---|---|
| Validity Period | 90 days |
| Renewal Frequency | Recommended: Every 60 days |
| Certificate Type | Domain Validated (DV) |
| Encryption | RSA 2048-bit or ECDSA P-256 |
We don't want to manually renew our certificates every 90 days. Instead, we set up a cron job to renew them automatically:
sudo crontab -e
Add the following line:
0 3 * * * certbot renew --quiet
Cron Job Breakdown:
0 3 * * *: Runs at 3:00 AM every daycertbot renew: Checks all certificates and renews those expiring within 30 days--quiet: Suppresses output unless there's an errorPerform a dry run to verify the renewal process works:
sudo certbot renew --dry-run
Expected Output:
Saving debug log to /var/log/letsencrypt/letsencrypt.log
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/yourdomain.com.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert not due for renewal, but simulating renewal for dry run
Plugins selected: Authenticator apache, Installer apache
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for yourdomain.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
new certificate deployed with reload of apache server; fullchain is
/etc/letsencrypt/live/yourdomain.com/fullchain.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations, all renewals succeeded.
Now, Certbot will automatically renew your SSL certificates every day at 3:00 AM.
Before transitioning into automation, I took an extra step to enhance server management via a browser interface by configuring Webmin. This tool provides a rich GUI for system administration tasks like user management, package updates, and more.
Webmin is a web-based system administration tool for Unix-like systems. It allows you to manage your server through a browser interface instead of the command line.
Webmin Features:
wget https://www.webmin.com/download/deb/webmin-current.deb
sudo dpkg -i webmin-current.deb
sudo apt --fix-broken install
Installation Commands Explained:
wget: Downloads the Webmin .deb package from official sourcesudo dpkg -i: Installs the .deb packagesudo apt --fix-broken install: Resolves any dependency issuesResolved permission error during the .deb install (see Troubleshooting section below)
Opened port 10000 for Webmin access in the Security Group
Accessed Webmin via browser at: https://your-server-ip:10000
Logged in with:
This gave me an alternative, secure way to manage the instance before proceeding with the CloudFormation setup in Part 2.
Webmin Dashboard Components:
| Section | Purpose |
|---|---|
| System | System information, logs, scheduled cron jobs |
| Servers | Apache, SSH, DNS, and other server management |
| Tools | File manager, custom commands, system shell |
| Networking | Network configuration, firewall rules |
| Hardware | Disk management, partitions, RAID |
| Webmin | Webmin configuration and module management |
Now that we've manually set up our server, let's make it repeatable. AWS CloudFormation allows us to automate the entire infrastructure deployment.
Infrastructure as Code (IaC) is the practice of managing and provisioning computing infrastructure through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.
Benefits of IaC with CloudFormation:
CloudFormation is like the blueprint of your AWS resources. It allows you to define and provision infrastructure using code. Here's a basic YAML template that launches an EC2 instance, sets up Apache, and configures security groups.
AWSTemplateFormatVersion: '2010-09-09'
Description: >
Launch an EC2 instance, install Apache web server, allow traffic on ports 80, 443, 22,
and 10000 (Webmin), and display a custom HTML page.
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access
Type: AWS::EC2::KeyPair::KeyName
ConstraintDescription: Must be the name of an existing EC2 KeyPair
InstanceType:
Description: EC2 instance type
Type: String
Default: t2.micro
AllowedValues:
- t2.micro
- t2.small
- t2.medium
ConstraintDescription: Must be a valid EC2 instance type
Resources:
WebServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable HTTP, HTTPS, SSH, and Webmin access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Description: SSH access
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
Description: HTTP access
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
Description: HTTPS access
- IpProtocol: tcp
FromPort: 10000
ToPort: 10000
CidrIp: 0.0.0.0/0
Description: Webmin access
WebServerInstance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
ImageId: ami-0c55b159cbfafe1f0 # Ubuntu 22.04 LTS (update for your region)
SecurityGroups:
- !Ref WebServerSecurityGroup
UserData:
Fn::Base64: !Sub |
#!/bin/bash
apt update
apt install -y apache2
systemctl enable apache2
systemctl start apache2
echo "<h1>🚀 CloudFormation Web Server</h1><p>This page was deployed automatically via CloudFormation.</p>" > /var/www/html/index.html
Outputs:
WebsiteURL:
Description: URL of the web server
Value: !Sub 'http://${WebServerInstance.PublicDnsName}'
InstanceId:
Description: Instance ID of the web server
Value: !Ref WebServerInstance
PublicIP:
Description: Public IP address of the web server
Value: !GetAtt WebServerInstance.PublicIp
Template Structure:
This template defines:
Why CloudFormation?
CloudFormation is perfect for Infrastructure as Code (IaC). It allows you to define your infrastructure in YAML or JSON and deploy it with the click of a button, ensuring consistency across multiple environments.
After writing the template, we deploy it as a CloudFormation Stack:
Deployment Steps:
CloudFormation will then take care of everything, from creating the EC2 instance to setting up Apache.
Stack Creation Process:
CREATE_IN_PROGRESS AWS::EC2::SecurityGroup WebServerSecurityGroup
CREATE_COMPLETE AWS::EC2::SecurityGroup WebServerSecurityGroup
CREATE_IN_PROGRESS AWS::EC2::Instance WebServerInstance
CREATE_COMPLETE AWS::EC2::Instance WebServerInstance
CREATE_COMPLETE AWS::CloudFormation::Stack WebServerStack
Expected Deployment Time: 3-5 minutes
Monitor the stack creation in the CloudFormation console:
Once our server is up and running, we connect our custom domain and install the SSL certificate.
We use Hostinger, GoDaddy, or any other domain provider to create an A record that points to our EC2 instance's IP address.
DNS Configuration Steps:
DNS Record Configuration:
| Record Type | Name | Value | TTL | Purpose |
|---|---|---|---|---|
| A | @ | 54.123.45.67 | 3600 | Root domain (yourdomain.com) |
| A | www | 54.123.45.67 | 3600 | WWW subdomain (www.yourdomain.com) |
DNS Propagation:
After updating DNS records, propagation can take 1-48 hours (typically 1-4 hours). You can check propagation status using:
nslookup yourdomain.com
dig yourdomain.com
We SSH into our EC2 instance and run the same Certbot commands as before to install SSL:
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
SSL Installation Process:
Now, our website is secure, and we have HTTPS running.
Verify SSL Installation:
sudo certbot certificates
Expected Output:
Found the following certs:
Certificate Name: yourdomain.com
Domains: yourdomain.com www.yourdomain.com
Expiry Date: 2024-04-15 10:30:25+00:00 (VALID: 89 days)
Certificate Path: /etc/letsencrypt/live/yourdomain.com/fullchain.pem
Private Key Path: /etc/letsencrypt/live/yourdomain.com/privkey.pem
No journey is without its challenges! During the manual setup, we encountered a few issues. Here's a breakdown of the errors, what caused them, and how we fixed them.
What Happened?
While trying to install Webmin using the .deb package on our EC2 instance, we encountered the following error:
N: Download is performed unsandboxed as root as file '/home/ubuntu/webmin_2.105_all.deb'
couldn't be accessed by user '_apt'. - pkgAcquire::Run (13: Permission denied)
Cause of the Issue:
This error occurs when the APT package manager (which handles package installation on Ubuntu) is run as root and doesn't have proper permissions for downloading the .deb package. The system is essentially trying to download the file without proper access rights.
How We Resolved It:
To resolve the issue, we had to fix the permissions of the directory where the file was being downloaded. Here's the fix we applied:
First, we cleaned up the directory and removed any partially downloaded files:
sudo rm -f /home/ubuntu/webmin_2.105_all.deb
We tried running the installation again, but with elevated privileges to ensure the download happened correctly:
sudo dpkg -i webmin_2.105_all.deb
Lesson Learned:
When installing packages via dpkg, it's important to ensure that the user running the command has the right permissions to download and install files. Running as root (without the proper environment) can sometimes interfere with the process, so checking permissions and file locations is critical.
What Happened?
After setting up Apache and configuring the default page, we tried accessing the server via http://your-ec2-ip, but received a 403 Forbidden error.
Cause of the Issue:
This error typically occurs when Apache is not configured to allow public access to the directory containing the web page, or if file permissions are not set correctly.
How We Resolved It:
Here's how we fixed the issue:
We ensured that the directory /var/www/html where Apache serves files had the correct permissions:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
Permission Explanation:
chown www-data:www-data: Sets Apache user as ownerchmod 755: Sets read/execute for everyone, write for owner onlyWe confirmed that Apache's configuration allowed access to the public directory. We edited the 000-default.conf file to make sure it allowed traffic:
sudo nano /etc/apache2/sites-available/000-default.conf
Then, we checked that the following lines were set up correctly:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
After modifying the configurations, we restarted Apache to apply the changes:
sudo systemctl restart apache2
Lesson Learned:
Permissions and Apache configurations are critical when setting up a web server. Always check both the filesystem permissions and the Apache configuration to ensure everything is set up correctly.
What Happened?
After configuring SSL with Let's Encrypt, we encountered a certificate installation failure.
Cause of the Issue:
This happened because the HTTP-01 challenge used by Let's Encrypt requires the server to be accessible over HTTP (port 80). However, since we didn't have port 80 open in our security group at the time, the certificate installation failed.
How We Resolved It:
To fix this, we:
We confirmed that port 80 was open in the EC2 security group.
After ensuring port 80 was open, we re-ran the Certbot command to obtain the SSL certificate:
sudo certbot --apache -d yourdomain.com
After Certbot successfully issued the certificate, we verified it by visiting the site via https://yourdomain.com.
Lesson Learned:
When using Let's Encrypt, it's essential to have port 80 open temporarily for the HTTP-01 challenge. Once the certificate is installed, we can secure the server with HTTPS, and traffic on port 80 can be redirected to HTTPS.
Let's Encrypt Challenge Types:
| Challenge Type | Required Port | Validation Method | Use Case |
|---|---|---|---|
| HTTP-01 | 80 | Serves file via HTTP | Standard web servers |
| DNS-01 | N/A | Creates TXT record in DNS | Wildcard certificates, servers behind firewall |
| TLS-ALPN-01 | 443 | TLS extension | Servers that can't open port 80 |
With the manual setup, we learned how to configure and secure a web server step by step. Then, we took that knowledge and automated it using AWS CloudFormation, simplifying future deployments. By connecting a custom domain and adding SSL, we've built a secure, scalable web server hosted on AWS.
Key Takeaways:
Use this template as a base for scaling and adding more services:
Explore integrating this setup with AWS Elastic Load Balancers or Auto Scaling for high availability:
Enhance Security:
Implement CI/CD Pipeline:
This AWS EC2 web server setup complements Azure-based infrastructure:
Cross-Platform Scenarios:
apt update && apt upgradeI hope this guide has made the process of setting up a web server on AWS EC2 more approachable. Whether you're just starting or have some experience under your belt, there's always something new to learn in the world of cloud computing. Stay tuned for more tutorials as we continue to automate and scale our cloud infrastructure!
Additional Learning Resources: