Get started with CloudFront - Part 1: CloudFront Distribution
Tags: aws, cloudfront, guide, networking
Published: 2023-02-28 19:10:38

#### 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:

1. **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.

2. **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.

3. **Custom Error Page**: You can customize your error page to be compatible with your website.

4. **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.

5. **Response Headers**: You can configure HTTP response headers to customize client requests.

6. **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.

7. **Create Lambda@Edge function**: If you want to process a CloudFront request, you can use the Lambda@Edge function.

8. **Deploy Lambda@Edge to CloudFront**: You can deploy your Lambda@Edge function to CloudFront using the AWS CLI.

9. **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

1. [Create EC2](2.1-createec2/)
2. [Create S3](2.2-creates3/)
3. [Create CloudFront Distribution]()
4. [Add EC2]()
5. [Test app]()


#### 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**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evpvzm9ochcvit3ibu7j.png)

Enter the instance name


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2imhi37i82cie4xy1n2.png)

Select **AMI** as **Amazon Linux**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfq1bpfm1b0672rocake.png)

Select **t2.micro**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vhnk8t3j4abguwe1i05.png)

Select **Create new key pair**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qnzuar7j78xxugc7v1k.png)

Enter the key name and select **Create key pair**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a97sc0mn0skmtoh2xbuz.png)

Configure networking

   - Select **VPC**
   - Create **security group**
   - Configure security according to the picture


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzm3an3m2hn483wzs6jq.png)

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
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zfl51ryqcy50trqz1iwp.png)

Select **Launch instance**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rpo0nhla03rv4i1oxvif.png)

Successful EC2 Creation


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tw2b4w66upchlc32mce.png)

View the details of the newly created EC2.



Copy **Public IPv4 DNS**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tuxhjwi7yhnpani6dlvz.png)

Use **Public IPv4 DNS** included with **/api**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5c1alot8n61188qtrcnc.png)

#### 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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3c2gbnd9agsi1os5n00.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9eo0f05gub9cwvxixbq1.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pgw02tvre35tjgfpiri.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3t4xqk4s4s94qctp7tg.png)

At the bucket interface, click the **Upload** button to upload the index.html file.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndpp3kwwhcudr63d44xh.png)

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.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lzughev375449s7w0b4.png)

Check the index.html . file


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d910xbw2oed2gaqaod1z.png)

When accessing the index.html file using the Object URL provided by Amazon S3.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p0vwvmkvry3qwurrmjhi.png)

You will see an access denied message because the file is not configured for public access.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdx55jav915slb4kdlbv.png)


#### Create CloudFront Distribution

Go to CloudFront on the AWS console and click Create a CloudFront Distribution.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdsilkkdtvt20bnpv17z.png)

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)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jht56pzfjw2ukff79l6e.png)

Origin access identity

   - Click Create new OAI



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74gr8j94zu5vifirqaj3.png)

- In the displayed dialog, click Create


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dtoy168412fa8xm6rklz.png)

Policy bucket > Yes, update the bucket policy


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7q89cgc0vzibb1h2aord.png)

Configure the Default Cache Behavior as follows:

   - View protocol policy > Redirect HTTP to HTTPS.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0skzlgxe2z5t3lf05c01.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87qei4zhq696vk61izmj.png)

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



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hsny2794qz57w0svkvbc.png)

Click Create distribution


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6657je3hc03czrkzs9b.png)

Create a successful CloudFront distribution.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ebxqtc16qb9th01gis2.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zgwrzqi6308f6z98wxzj.png)


#### 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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2vvz1t1rdh1leyymz0z.png)

Enter the DNS name of the EC2 instance in the Origin Domain Name field. Configure by setting Origin Protocol Policy to HTTP only.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/813jbz1u4ss14aayxval.png)

Keep defaults and select **Additional settings**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/peuemvvmu20aov2w9xrp.png)

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**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b56ychon8bhiu2eq1jpb.png)

Create origin successfully


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74utfl7drgtoo81jv6kn.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmze56rk0zywo3rj8e8g.png)

Path pattern > /api

- Origin and origin groups > Select previously created EC2 Origin


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96692kurj59s0k7p4h8h.png)

Viewer protocol policy > Redirect HTTP to HTTPS



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96euv1s8nyjbnav4ksd5.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5u5ilb9fctb7jivxpkd.png)

Select **Create behavior**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z63tm4y1pg3a7csshess.png)

Create successful behavior.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9ngrz94q2rf9b2qw6w9.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6qlw8pvoatgamas2orf.png)


#### 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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/psyemcgdaza29cykdxiy.png)

- Make a connection to EC2.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzoaabzvoox8eo38uzqz.png)

- 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:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bi2bewxw40v7l3pmt5qp.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pnl82um10l5u5hotevz.png)

- 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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnituo984d8ix9x3y4ed.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7f3zgsaebap3qx9bgq36.png)

- 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.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zysnczoqheuwdqybzdmi.png)

- 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](https://dev.to/aws-builders/get-started-with-cloudfront-cloudfront-distribution-2n1m)

[Get started with CloudFront - Part 2: Distribution Invalidations](https://dev.to/aws-builders/get-started-with-cloudfront-part-2-distribution-invalidations-2d4)

[Get started with CloudFront - Part 3: Response Headers and Cache Behavior](https://dev.to/aws-builders/get-started-with-cloudfront-part-3-response-headersand-cache-behavior-2n5e)

[Get started with CloudFront - Part 4: Lambda@Edge function](https://dev.to/aws-builders/get-started-with-cloudfront-part-4-lambdaedge-function-4cbh)