>  기사  >  웹 프론트엔드  >  AWS Cloud Resume 챌린지 블로그 게시물 1부

AWS Cloud Resume 챌린지 블로그 게시물 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을 서핑하다가 Cloud Resume Challenge에 대해 들었습니다. 기술에 열광하지만 매일 AWS에서 일하지는 않는 사람으로서 이 도전에 흥미를 느꼈습니다. 

Forrest Brazeal이 만든 Cloud Resume Challenge는 다양한 AWS 서비스를 사용하여 풀 스택 애플리케이션을 구축하는 다단계 프로젝트입니다. 실제 구현을 통해 클라우드 기술을 보여주도록 설계되었으므로 이미 현장에 있는 사람들에게도 훌륭한 연습이 됩니다.

이 블로그 게시물에서는 Cloud Resume Challenge를 완료한 경험을 공유하고, 제가 사용한 AWS 서비스, 구현한 아키텍처, 얻은 통찰력을 자세히 설명하겠습니다. 기술을 연마하려는 클라우드 전문가이거나 실제 AWS 애플리케이션에 대해 궁금한 사람이라면 이 프로젝트를 통해 제 여정에서 가치를 발견할 수 있기를 바랍니다.

목차

  1. 소개
  2. S3를 사용하여 정적 웹사이트 설정
  3. CloudFront로 웹사이트 보안
  4. Route 53으로 DNS 구성
  5. 방문자 카운터 구현
  6. 프런트엔드 JavaScript 통합
  7. JavaScript 코드 테스트
  8. 결론

소개

클라우드 네이티브 개발은 클라우드 컴퓨팅의 성능을 활용하여 확장 가능하고 탄력적인 애플리케이션을 구축합니다. 이 종합 가이드에서는 다양한 AWS 서비스를 사용하여 클라우드 네이티브 웹 사이트를 생성하는 과정을 안내합니다. 우리는 정적 웹사이트 호스팅부터 시작하여 점진적으로 방문자 카운터를 포함한 동적 기능을 추가할 것입니다. 이 문서는 다양한 AWS 서비스가 어떻게 함께 작동하여 완벽하게 기능하고 확장 가능한 웹 사이트를 생성하는지 이해하려는 초보자에게 적합합니다.

S3를 사용하여 정적 웹 사이트 설정

Amazon S3(Simple Storage Service)는 정적 웹사이트를 호스팅하는 데 사용할 수 있는 객체 스토리지 서비스입니다. 설정 방법은 다음과 같습니다.

  1. S3 버킷 생성:

    • AWS Management Console로 이동하여 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. 오리진 액세스 ID(OAI) 설정:

    • OAI를 생성하여 배포판과 연결하세요.
    • 이 OAI에서만 액세스를 허용하도록 S3 버킷 정책을 업데이트하세요.

Route 53으로 DNS 구성

Route 53은 AWS의 DNS(Domain Name System) 웹 서비스입니다. 이를 사용하여 도메인 이름을 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 Cloud Resume 챌린지 블로그 게시물 1부의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.