首頁  >  文章  >  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