“使用 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中文网其他相关文章!