首页  >  文章  >  web前端  >  AWS 云简历挑战博客文章第 1 部分

AWS 云简历挑战博客文章第 1 部分

WBOY
WBOY原创
2024-08-02 07:33:121114浏览

AWS Cloud Resume Challenge Blog Post Part 1

“使用 AWS 构建云原生网站:从静态托管到动态内容”

  1. 简介
  2. 使用 S3 设置静态网站
  3. 使用 CloudFront 保护网站
  4. 使用 Route 53 配置 DNS
  5. 实施访客计数器
    • 用于数据存储的 DynamoDB
    • 用于后端逻辑的 Lambda
    • HTTP 端点的 API 网关
  6. 前端 JavaScript 集成
  7. 测试 JavaScript 代码
  8. 结论

使用 AWS 构建云原生网站:从静态托管到动态内容

几年前我在 Reddit 上冲浪时听说了云简历挑战赛。作为一名技术爱好者,但并不是每天都在 AWS 工作的人,这个挑战引起了我的兴趣。 

云简历挑战赛由 Forrest Brazeal 创建,是一个多步骤项目,涉及使用各种 AWS 服务构建全堆栈应用程序。它旨在通过实际实施展示云技能,即使对于我们这些已经在该领域的人来说也是一个很好的练习。

在这篇博文中,我将分享我完成云简历挑战赛的经验,详细介绍我使用的 AWS 服务、我实施的架构以及我获得的见解。无论您是希望提高技能的云专业人士,还是对现实世界的 AWS 应用程序感到好奇的人,我希望您能在我的这个项目之旅中发现价值。

目录

  1. 简介
  2. 使用 S3 设置静态网站
  3. 使用 CloudFront 保护网站
  4. 使用 Route 53 配置 DNS
  5. 实施访客计数器
  6. 前端 JavaScript 集成
  7. 测试 JavaScript 代码
  8. 结论

介绍

云原生开发利用云计算的力量来构建可扩展且有弹性的应用程序。在本综合指南中,我们将逐步介绍使用各种 AWS 服务创建云原生网站的过程。我们将从托管静态网站开始,并逐步添加动态功能,包括访客计数器。本文非常适合想要了解不同 AWS 服务如何协同工作以创建功能齐全、可扩展网站的初学者。

使用 S3 设置静态网站

Amazon S3(简单存储服务)是一种对象存储服务,我们可以使用它来托管静态网站。设置方法如下:

  1. 创建 S3 存储桶:

    • 转到 AWS 管理控制台并导航到 S3。
    • 点击“创建存储桶”并选择一个全局唯一的名称。
    • 在存储桶设置中,启用“静态网站托管”。
    • 将索引文档设置为“index.html”。
  2. 上传您的网站文件:

    • 将您的 HTML、CSS 和 JavaScript 文件上传到存储桶。
    • 确保文件具有公共读取权限。
  3. 配置存储桶策略:

    • 在存储桶权限中,添加存储桶策略以允许公共读取访问:
   {
       "Version": "2012-10-17",
       "Statement": [
           {
               "Sid": "PublicReadGetObject",
               "Effect": "Allow",
               "Principal": "*",
               "Action": "s3:GetObject",
               "Resource": "arn:aws:s3:::your-bucket-name/*"
           }
       ]
   }

将“your-bucket-name”替换为您的实际存储桶名称。

使用 CloudFront 保护网站

CloudFront 是 AWS 的内容交付网络 (CDN) 服务。我们将使用它通过 HTTPS 为我们的网站提供服务并提高性能:

  1. 创建 CloudFront 发行版:

    • 在 AWS 控制台中,转到 CloudFront 并单击“创建分配”。
    • 将源域设置为您的 S3 存储桶的网站端点。
    • 启用“将 HTTP 重定向到 HTTPS”。
  2. 配置 SSL/TLS 证书:

    • 使用 AWS Certificate Manager (ACM) 为您的域创建免费的 SSL/TLS 证书。
    • 在您的 CloudFront 分配设置中,选择此证书。
  3. 设置源访问身份(OAI):

    • 创建 OAI 并将其与您的发行版关联。
    • 更新您的 S3 存储桶策略以仅允许从此 OAI 进行访问。

使用 Route 53 配置 DNS

Route 53 是 AWS 的域名系统 (DNS) Web 服务。我们将使用它将我们的域名映射到我们的 CloudFront 分配:

  1. 创建托管区域:

    • 在 Route 53 中,为您的域创建托管区域。
  2. 更新名称服务器:

    • 如果您的域在其他地方注册,请更新您的注册商处的名称服务器以使用 Route 53 的名称服务器。
  3. 创建记录集:

    • Create an A record for your domain, aliasing it to your CloudFront distribution.
    • If needed, create a CNAME record for www subdomain.

Implementing a Visitor Counter

For our visitor counter, we'll use a serverless architecture with DynamoDB, Lambda, and API Gateway.

DynamoDB for Data Storage

DynamoDB is a NoSQL database service. We'll use it to store our visitor count:

  1. Create a DynamoDB table:
    • Name: "VisitorCount"
    • Partition key: "id" (String)
    • Add an item with id "visitors" and an attribute "count" set to 0.

Lambda for Backend Logic

Lambda allows us to run code without provisioning servers. Our Lambda function will update the visitor count:

  1. Create a Lambda function:
    • Runtime: Node.js 20.x
    • Code:
   const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');

   const client = new DynamoDBClient();

   exports.handler = async (event) => {
       const params = {
           TableName: process.env.TABLE_NAME,
           Key: { id: { S: 'visitors' } },
           UpdateExpression: 'ADD visitorCount :inc',
           ExpressionAttributeValues: { ':inc': { N: '1' } },
           ReturnValues: 'UPDATED_NEW'
       };

       try {
           const command = new UpdateItemCommand(params);
           const data = await client.send(command);

           const visitorCount = data.Attributes.visitorCount.N;

           return {
               statusCode: 200,
               headers: {
                   "Access-Control-Allow-Origin": "https://yourdomain.com",
                   "Access-Control-Allow-Headers": "Content-Type",
                   "Access-Control-Allow-Methods": "OPTIONS,POST"
               },
               body: JSON.stringify({ visitorCount: parseInt(visitorCount) })
           };
       } catch (error) {
           console.error('Error:', error);
           return {
               statusCode: 500,
               headers: {
                   "Access-Control-Allow-Origin": "https://yourdomain.com",
                   "Access-Control-Allow-Headers": "Content-Type",
                   "Access-Control-Allow-Methods": "OPTIONS,POST"
               },
               body: JSON.stringify({ error: 'Failed to update visitor count' })
           };
       }
   };
  1. Set up environment variables:

    • Add TABLE_NAME environment variable with your DynamoDB table name.
  2. Configure permissions:

    • Give the Lambda function permission to read/write to your DynamoDB table.

API Gateway for HTTP Endpoints

API Gateway allows us to create, publish, and manage APIs. We'll use it to expose our Lambda function:

  1. Create a new API:

    • Choose HTTP API type.
  2. Create a resource and method:

    • Create a resource named "visitorcount".
    • Add a POST method to this resource, integrating it with your Lambda function.
  3. Enable CORS:

    • In the API settings, enable CORS for your domain.
  4. Deploy the API:

    • Create a new stage (e.g., "prod") and deploy your API.

Frontend JavaScript Integration

Now, let's integrate our backend with the frontend:

  1. Add HTML for the visitor counter:
   <div id="visitor-count">Visitors: <span id="count">0</span></div>
  1. Add JavaScript to call our API:
   function updateVisitorCount() {
       fetch('https://your-api-gateway-url/visitorcount', {
           method: 'POST',
           headers: {
               'Content-Type': 'application/json'
           },
           mode: 'cors'
       })
       .then(response => response.json())
       .then(data => {
           document.getElementById('count').textContent = data.visitorCount;
       })
       .catch(error => console.error('Error:', error));
   }

   document.addEventListener('DOMContentLoaded', updateVisitorCount);

Replace 'https://your-api-gateway-url' with your actual API Gateway URL.

Testing the JavaScript Code

To ensure our JavaScript works correctly, we'll add some tests:

  1. Install Jest for testing:
   npm install --save-dev jest
  1. Create a test file (e.g., visitorCounter.test.js):
   // Mock fetch function
   global.fetch = jest.fn(() =>
     Promise.resolve({
       json: () => Promise.resolve({ visitorCount: 5 }),
     })
   );

   // Import the function to test
   const { updateVisitorCount } = require('./visitorCounter');

   test('updates visitor count correctly', async () => {
     // Set up our document body
     document.body.innerHTML = '<div id="count">0</div>';

     // Call the function
     await updateVisitorCount();

     // Check that the count was updated
     expect(document.getElementById('count').textContent).toBe('5');
   });
  1. Run the tests:
   npx jest

Conclusion

In this guide, we've covered how to build a cloud-native website using various AWS services. We've implemented a static website with S3, secured it with CloudFront, set up DNS with Route 53, and created a serverless backend with DynamoDB, Lambda, and API Gateway.

This architecture provides a scalable, secure, and cost-effective solution for hosting websites and web applications. As you become more comfortable with these services, you can expand on this foundation to build even more complex and feature-rich applications.

In the next article, we'll explore how to automate the deployment of this website using CI/CD practices with GitHub Actions.

以上是AWS 云简历挑战博客文章第 1 部分的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn