ホームページ  >  記事  >  ウェブフロントエンド  >  AWS クラウド再開チャレンジのブログ投稿パート 1

AWS クラウド再開チャレンジのブログ投稿パート 1

WBOY
WBOYオリジナル
2024-08-02 07:33:121114ブラウズ

AWS Cloud Resume Challenge Blog Post Part 1

「AWS を使用したクラウドネイティブ Web サイトの構築: 静的ホスティングから動的コンテンツまで」

  1. はじめに
  2. S3 を使用した静的 Web サイトのセットアップ
  3. CloudFront を使用して Web サイトを保護する
  4. Route 53 を使用した DNS の構成
  5. 訪問者カウンターの実装
    • データストレージ用の DynamoDB
    • バックエンド ロジック用の Lambda
    • HTTP エンドポイント用の API ゲートウェイ
  6. フロントエンド JavaScript の統合
  7. JavaScript コードのテスト
  8. 結論

AWS を使用したクラウドネイティブ Web サイトの構築: 静的ホスティングから動的コンテンツまで

私は数年前に Reddit をサーフィンしていたときに Cloud Resume Challenge について知りました。テクノロジー愛好家ではあるものの、AWS で日常的に働いているわけではない私は、この挑戦​​に興味をそそられました。 

Forrest Brazeal によって作成された Cloud Resume Challenge は、さまざまな AWS サービスを使用してフルスタック アプリケーションを構築する複数ステップのプロジェクトです。実践的な実装を通じてクラウド スキルを披露するように設計されており、すでに現場にいる人にとっても優れた演習になります。

このブログ投稿では、Cloud Resume Challenge を完了した私の経験を共有し、使用した AWS サービス、実装したアーキテクチャ、得た洞察について詳しく説明します。あなたがスキルを磨きたいと考えているクラウド プロフェッショナルであっても、実際の AWS アプリケーションに興味がある人であっても、このプロジェクトを通じた私の取り組みに価値を見出していただければ幸いです。

目次

  1. はじめに
  2. S3 を使用した静的 Web サイトのセットアップ
  3. CloudFront を使用して Web サイトを保護する
  4. Route 53 を使用した DNS の構成
  5. 訪問者カウンターの実装
  6. フロントエンド JavaScript の統合
  7. JavaScript コードのテスト
  8. 結論

導入

クラウドネイティブ開発では、クラウド コンピューティングの力を活用して、スケーラブルで復元力のあるアプリケーションを構築します。この包括的なガイドでは、さまざまな AWS サービスを使用してクラウドネイティブ Web サイトを作成するプロセスについて説明します。まずは静的 Web サイトのホスティングから始めて、訪問者カウンターなどの動的機能を徐々に追加していきます。この記事は、さまざまな AWS サービスがどのように連携して完全に機能し、スケーラブルなウェブサイトを作成するかを理解したい初心者に最適です。

S3 を使用した静的 Web サイトのセットアップ

Amazon S3 (Simple Storage Service) は、静的 Web サイトをホストするために使用できるオブジェクト ストレージ サービスです。設定方法は次のとおりです:

  1. S3 バケットを作成します:

    • AWS マネジメントコンソールに移動し、S3 に移動します。
    • [バケットの作成] をクリックし、グローバルに一意の名前を選択します。
    • バケット設定で、「静的 Web サイト ホスティング」を有効にします。
    • インデックスドキュメントを「index.html」に設定します。
  2. Web サイトのファイルをアップロードします:

    • 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 を使用して Web サイトを保護する

CloudFront は、AWS のコンテンツ配信ネットワーク (CDN) サービスです。これを使用して、HTTPS 経由で Web サイトを提供し、パフォーマンスを向上させます:

  1. CloudFront ディストリビューションを作成します:

    • AWS コンソールで、CloudFront に移動し、[ディストリビューションの作成] をクリックします。
    • オリジンドメインを S3 バケットの Web サイトエンドポイントに設定します。
    • 「HTTP を HTTPS にリダイレクト」を有効にします。
  2. SSL/TLS 証明書を構成します:

    • AWS Certificate Manager (ACM) を使用して、ドメイン用の無料の SSL/TLS 証明書を作成します。
    • CloudFront 配布設定で、この証明書を選択します。
  3. Origin Access Identity (OAI) のセットアップ:

    • OAI を作成し、ディストリビューションに関連付けます。
    • この OAI からのアクセスのみを許可するように S3 バケット ポリシーを更新します。

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。