Overview
Amazon CloudFront is the static and dynamic content delivery service of Amazon Web Services (AWS). With the ability to increase the speed and stability of your web applications, Amazon CloudFront provides a temporary storage solution for your content on Amazon Edge servers.
Amazon CloudFront is customizable and flexible allowing you to configure features such as EC2 and S3 Origins, CloudFront Distribution, Custom Error Page, Origin Group, Response Headers, create new cache behavior, create Lambda@Edge function and deploy Lambda@Edge function to CloudFront. This increases content availability and reduces response times.
In addition, Amazon CloudFront provides features that monitor and analyze the performance of content delivered through this service. By logging in to S3 and using tools like Amazon Athena and Amazon Redshift, you can easily monitor and analyze the performance of your assets.
To help you better understand Amazon CloudFront, let's look at some of its features and usage:
EC2 and S3 Origins: Amazon CloudFront allows you to connect content from EC2 or S3. This increases the speed and reduces the response time of your web application.
CloudFront Distribution: To use Amazon CloudFront, you need to create a distribution. Distribution is a collection of Amazon's Edge servers, on which your content is temporarily stored.
Custom Error Page: You can customize your error page to be compatible with your website.
Origin Group: If you have multiple Origin servers, you can configure them into a group. CloudFront will automatically switch to other servers in the pool if the origin server crashes.
Response Headers: You can configure HTTP response headers to customize client requests.
Create a new cache behavior: If you want to create a new cache behavior, you need to configure its features on the origin server or by using Lambda@Edge.
Create Lambda@Edge function: If you want to process a CloudFront request, you can use the Lambda@Edge function.
Deploy Lambda@Edge to CloudFront: You can deploy your Lambda@Edge function to CloudFront using the AWS CLI.
Metrics and Logs: Amazon CloudFront provides features to monitor and analyze the performance of content delivered through this service. By logging in to S3 and using tools like Amazon Athena and Amazon Redshift, you can easily monitor and analyze the performance of your assets.
As such, Amazon CloudFront is a great service to increase the speed and stability of your web application. With its features and strengths, Amazon CloudFront is a reliable and flexible content delivery solution.
Best practice
To get the most out of Amazon CloudFront's potential, there are a few best practices that you should follow:
Use S3 Bucket or EC2 Instance as Origin: Using S3 Bucket or EC2 Instance as Origin for your CloudFront Distribution will increase response speed and reduce bandwidth costs.
Use SSL/TLS Encryption: Use SSL/TLS Encryption to protect data in transit between Origin and Edge Locations. You can use a free or paid SSL certificate to ensure the security of your data.
Use Compression: Use compression in CloudFront Distribution to reduce file size and speed up page loading.
Use CloudFront Behaviors: Create CloudFront Behaviors to customize how CloudFront handles requests. For example, you can create a cache behavior to optimize performance for GET or HEAD requests.
Use Caching: Use the caching feature in CloudFront to reduce page load times and reduce bandwidth costs. You can configure the cache to cache resources temporarily and reduce the number of requests to the origin.
Use Lambda@Edge: Use Lambda@Edge to customize and process customer requests on CloudFront. Lambda@Edge provides the ability to add, modify, or remove HTTP headers or resources on your site.
Use AWS WAF: Use AWS WAF to protect your applications on CloudFront. AWS WAF provides security policies, filters, and access management for your applications.
Use CloudFront Logs: Use the logging feature in CloudFront to monitor and analyze the performance of your delivered assets. You can use data analytics tools, like Amazon Athena or Amazon Redshift, to analyze logs and make smart business decisions.
Preparation steps
To get the most out of Amazon CloudFront, you need to create origins for your content. These origins will contain data and are used by CloudFront to deliver content to end users. The two primary origins for use with Amazon CloudFront are Amazon S3 (Simple Storage Service) and Amazon EC2 (Elastic Compute Cloud).
Amazon S3 (Simple Storage Service): If you are using Amazon S3 to store content, you can create an S3 bucket as the origin for CloudFront. An S3 bucket is a simple storage space for storing objects such as images, videos, or documents. After creating an S3 bucket, you can inject objects into it and use this S3 bucket as the origin for CloudFront.
Amazon EC2 (Elastic Compute Cloud): If you are using Amazon EC2 to run your application, you can create an EC2 instance as the origin for CloudFront. An EC2 instance is a virtual machine running on Amazon's cloud platform. After creating an EC2 instance, you can install and configure your application on it, and then use this EC2 instance as the origin for CloudFront.
Originating your content is essential to using Amazon CloudFront effectively. If you are using Amazon S3 or Amazon EC2, it is very simple to create an origin for CloudFront. Using these sources makes it possible to quickly and securely distribute your content.
Content
Create EC2
- Amazon EC2 (Elastic Compute Cloud): If you are using Amazon EC2 to run your application, you can create an EC2 instance as the origin for CloudFront. An EC2 instance is a virtual machine running on Amazon's cloud platform. After creating an EC2 instance, you can install and configure your application on it, and then use this EC2 instance as the origin for CloudFront.
Access to EC2
- Select Instances
- Select Launch instances
Enter the instance name
Select AMI as Amazon Linux
Select t2.micro
Select Create new key pair
Enter the key name and select Create key pair
Configure networking
- Select VPC
- Create security group
- Configure security according to the picture
Scroll down to the User data section, enter the following script:
#!/bin/bash
#Update the system and install Node.js
yum update -y
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
yum install -y nodejs
#Install PM2 and Express
npm install pm2@latest -g
npm install express --save
#Create and configure the Express app
cat <<'EOF' >> app.js
let express = require('express');
let app = express();
app.get('/api', (req, res) => {
console.log(JSON.stringify(req.headers));
let message = {
timestamp: new Date().toISOString(),
headers: req.headers,
};
res.json(message);
});
app.listen(80, () => {
console.log('api is up!');
});
EOF
#Start the app with PM2
sudo pm2 start ./app.js
sudo pm2 startup systemd
sudo pm2 save
#Enable PM2 to start on system boot
systemctl enable --now pm2-root.service
Select Launch instance
Successful EC2 Creation
View the details of the newly created EC2.
Copy Public IPv4 DNS
Use Public IPv4 DNS included with /api
Create S3
Sign in to the Amazon Web Services (AWS) S3 management page at https://console.aws.amazon.com/s3/.
Click the Create bucket button to start the process of creating a new bucket.
Enter the bucket name. The bucket name must be unique throughout the S3 system and cannot contain spaces.
Select the storage area (Region) for the bucket. The storage area will affect the access speed and hosting price. You should choose an area close to the user to optimize access speed.
Select other options as needed. AWS provides many options for configuring the bucket, such as encrypting data, sharing the bucket with other users, configuring access permissions, and more.
Click the Create bucket button to complete the bucket creation process.
After creating the bucket, you can access the bucket and add, delete, and edit files in it. To access the bucket, you can use the browser or the AWS SDK management tools.
Instructions to create index.html file on Amazon S3
Create file index.html
- Open a text editor on your computer and create a new file named index.html. Paste the following HTML content into this file:
<!DOCTYPE html>
<html lang="en">
<body>
<table border="1" width="100%">
<thead>
<tr>
<td><h1>CloudFront Lab</h1></td>
</tr>
</thead>
<tfoot>
<tr>
<td>Immersion Days - Edge Services - Module 1</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Response sent by API</td>
</tr>
</tbody>
<tbody>
<tr>
<td>
<iframe src="/api" style="width: 100%; height: 100%"></iframe>
</td>
</tr>
</tbody>
</table>
</body>
</html>
- Save the index.html file to an easy-to-remember address on your computer.
Upload index.html file to Amazon S3
- Go to the Amazon S3 console and select the bucket that was created.
At the bucket interface, click the Upload button to upload the index.html file.
In the next window, click the Add files button and select the index.html file from your computer. Then, click the Next button to go to the next page.
- On this page, leave all default settings and click the Next button again. Continue to set other settings and click the Upload button to complete the upload.
Check the index.html . file
When accessing the index.html file using the Object URL provided by Amazon S3.
You will see an access denied message because the file is not configured for public access.
Create CloudFront Distribution
Go to CloudFront on the AWS console and click Create a CloudFront Distribution.
Configure the default source for the previously created S3 bucket and grant CloudFront access to the bucket using the Origin Access Identity setup:
- Origin domain > Select your S3 bucket
- Access S3 bucket > Yes using OAI (bucket can limit access only to CloudFront)
Origin access identity
- Click Create new OAI
- In the displayed dialog, click Create
Policy bucket > Yes, update the bucket policy
Configure the Default Cache Behavior as follows:
- View protocol policy > Redirect HTTP to HTTPS.
Cache key and origin requests
- Cache policy and origin request policy (recommended)
- Cache policy > CachingOptimized (Recommended for S3 source) CloudFront provides a set of managed cache policies that you can attach to any cache behavior of your distribution. With a managed cache policy, you don't need to write or maintain your own cache policy. Management policies use settings optimized for specific use cases.
In the Settings section:
- In this lab you will use a domain name provided by CloudFront, however, if you want to use your own domain name, you can configure it with Alternate Domain Names , you can add a new entry in the section Alternate domain name (CNAME) - optional.
- Configure the Default root object - optionally index.html- And leave all remaining values ββas default
Click Create distribution
Create a successful CloudFront distribution.
CloudFront starts creating the distribution and it usually takes 5 to 10 minutes to fully deliver. The status of the delivery will be In Progress. To check the status, you can click on the Distribution menu on the left sidebar.
Add EC2 Origin
Access the CloudFront distribution management page.
Select the distribution ID corresponding to the site you want to configure.
Select the Origins tab.
Check existing origins. If you already have an origin, press the Create Origin button to add a new origin.
At the Origins page, click the Create Origin button to create a new origin for the API.
Enter the DNS name of the EC2 instance in the Origin Domain Name field. Configure by setting Origin Protocol Policy to HTTP only.
Keep defaults and select Additional settings
Increase keep alive timeout to 60 seconds.
Note that although we want to serve content over HTTPS to users, we want to keep the HTTP connection to origin to minimize the overhead of TLS.
- Select Create origin
Create origin successfully
Configure a second Behavior cache to use EC2's origin with the following parameters to use CloudFront as a proxy and ignore any cache classes.
Path pattern > /api
- Origin and origin groups > Select previously created EC2 Origin
Viewer protocol policy > Redirect HTTP to HTTPS
Cache key and origin requests
- Cache policy and origin request policy (recommended)
- Cache policy > CachingDisabled
- Origin request policy - options -> AllViewer
- In the above configuration, we use two types of management policy, CachingDisabled is a managed cache policy -- this policy disables cache, it is useful for dynamic content and for requests that cannot be handled cached -- and AllViewer is an origin-managed request policy -- this policy includes all values ββ(header, cookie and query string) in the viewer's request.
Select Create behavior
Create successful behavior.
Check the application
When you create a new CloudFront distribution, it will be in progress and it will take some time to spread to all the points of presence globally. However, you can check if the distribution is ready for local use by looking up its CloudFront domain with the nslookup command in the command line. When you lookup a CloudFront domain, CloudFront returns multiple IP addresses to increase application availability.
Once the distribution has reached all points of presence, the delivery's status will change to deployed (deployed) and you can use it on your web browser using your own CloudFront URL.
Access to EC2
- Make a connection to EC2.
- Once the distribution is complete, you can test your web page on your browser served by CloudFront using your CloudFront URL http://dxxxx.cloudfront.net.
In the web page, you can see the various headers that CloudFront forwarded and attached to your API endpoint:
x-amz-cf-id: A unique id for this request provided by CloudFront. If you refresh the site you will see that the request id changes. It's useful to log it on your web server in general. Additionally, this id will be sent back to every viewer request and sent to the CloudFront access log. If you need to debug any issue, you can open a support ticket and give them the request id.
Notice how CloudFront redirected the request to HTTPS.
- If you use your favorite web browser development tools, you can check the response headers sent by CloudFront. Three notable titles to check out:
x-amz-cf-id: Contains the request id assigned by CloudFront.
x-amz-cf-pop: Indicates the location of the CloudFront edge that served your request. Each edge position is identified by a three-letter code and an arbitrary number, for example, DFW3. The three-letter code usually corresponds to the International Air Transport Association airport code for an airport near the edge location.
x-cache: Indicates whether the request was evaluated as a pass or fail. Normally for your html file you will get 'Hit from Cloudfront' value in subsequent requests, but always 'Miss from CloudFront' for /api request because caching has been disabled for this behavior.
This means that if you visit your site again, the request will be retrieved from the cache and returned with the results stored in it instead of having to reload from the original server, improving time. load pages and increase performance. However, if you make changes to your site, you may want to refresh the cache to ensure that your users see the latest changes.
- In case you need to access the distribution from a different geographic region, you can use CloudFront's alternate domains, including domain names for each of the different geographies. This helps ensure that users in each region are served by their nearest CloudFront edge, which optimizes page load times and minimizes latency.
If you need to create a copy of an existing CloudFront distribution, you can use the clone feature to create an exact copy of the current distribution. This can be useful when you need to serve another version of your website or application at the same time, or when you need to deal with any issues with an existing distribution.
When you need to set up access policies to limit access to your distribution, you can use CloudFront's access management feature. This allows you to set up access policies based on IP address, domain name, HTTP method and more, helping to ensure that only authorized users can access your distribution. Friend.
Finally, if you need assistance from the AWS technical team, you can open a support ticket and provide details about your issue, including CloudFront request IDs and other information about your issue. your distribution. The AWS technical team will try to assist you in resolving your issue as soon as possible.
The following sections
Get started with CloudFront - Part 1: CloudFront Distribution
Get started with CloudFront - Part 2: Distribution Invalidations
Get started with CloudFront - Part 3: Response Headers and Cache Behavior
Top comments (1)
Thanks for the nice detail on Cloudfront.
I recently did a migration, and am only a beginner AWS enthusiast. But did run into some problems I would like to share.
please read my dev article
dev.to/rickdelpo1/cloudfront-dns-m...
Could u and ur team provide some feedback on some of my findings?
thanks very much