「使用 AWS 建立雲端原生網站:從靜態託管到動態內容」
幾年前我在 Reddit 上沖浪時聽說了雲簡歷挑戰賽。身為一個科技愛好者,但並不是每天都在 AWS 中工作的人,這項挑戰引起了我的興趣。
雲端履歷表挑戰賽由 Forrest Brazeal 創建,是一個多步驟項目,涉及使用各種 AWS 服務建立全端應用程式。它旨在透過實際實施來展示雲端技能,即使對於我們這些已經在該領域工作的人來說也是一個很好的練習。
在這篇文章中,我將分享我完成雲端履歷挑戰賽的經驗,詳細介紹我使用的 AWS 服務、我實施的架構以及我獲得的見解。無論您是希望提高技能的雲端專業人士,還是對現實世界的 AWS 應用程式感到好奇的人,我希望您能在我的這個專案之旅中發現價值。
雲端原生開發利用雲端運算的力量來建立可擴展且有彈性的應用程式。在本綜合指南中,我們將逐步介紹使用各種 AWS 服務建立雲端原生網站的過程。我們將從託管靜態網站開始,並逐步添加動態功能,包括訪客計數器。本文非常適合想要了解不同 AWS 服務如何協同工作以建立功能齊全、可擴展網站的初學者。
Amazon S3(簡單儲存服務)是一種物件儲存服務,我們可以使用它來託管靜態網站。設定方法如下:
建立 S3 儲存桶:
上傳您的網站檔案:
設定儲存桶策略:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::your-bucket-name/*" } ] }
將「your-bucket-name」替換為您的實際儲存桶名稱。
CloudFront 是 AWS 的內容交付網路 (CDN) 服務。我們將使用它透過 HTTPS 為我們的網站提供服務並提高效能:
建立 CloudFront 發行版:
設定 SSL/TLS 憑證:
設定來源存取身分(OAI):
Route 53 是 AWS 的網域名稱系統 (DNS) Web 服務。我們將使用它將我們的網域映射到我們的 CloudFront 分配:
建立託管區域:
更新名稱伺服器:
建立記錄集:
For our visitor counter, we'll use a serverless architecture with DynamoDB, Lambda, and API Gateway.
DynamoDB is a NoSQL database service. We'll use it to store our visitor count:
Lambda allows us to run code without provisioning servers. Our Lambda function will update the visitor count:
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' }) }; } };
Set up environment variables:
Configure permissions:
API Gateway allows us to create, publish, and manage APIs. We'll use it to expose our Lambda function:
Create a new API:
Create a resource and method:
Enable CORS:
Deploy the API:
Now, let's integrate our backend with the frontend:
<div id="visitor-count">Visitors: <span id="count">0</span></div>
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.
To ensure our JavaScript works correctly, we'll add some tests:
npm install --save-dev jest
// 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'); });
npx jest
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中文網其他相關文章!