服務器創建多個dhcp服務
by Charlee Li
通過李李
如何在15分鐘內創建無服務器服務 (How to create a serverless service in 15 minutes)
The word “serverless” has been popular for quite a while. When Amazon released the AWS Lambda service in 2015, many tools emerged to help people build serverless services with just a few commands. Compared to traditional always-on services, serverless services are very easy to develop, deploy and maintain. They’re also extremely cost effective, especially for those simple services which do not have too much traffic.
“無服務器”一詞已經流行了很長時間。 當亞馬遜于2015年發布AWS Lambda服務時,出現了許多工具,可幫助人們僅需幾個命令即可構建無服務器服務。 與傳統的永遠在線服務相比,無服務器服務非常易于開發,部署和維護。 它們也極具成本效益,特別是對于那些沒有太多流量的簡單服務。
那么什么是無服務器? (So what is serverless?)
As its name implies, “serverless” means that you run a service without a server. Well, technically, there is still a server running the service, but you, as the service owner, do not need to worry about that server.
顧名思義,“無服務器”意味著您無需服務器即可運行服務。 嗯,從技術上講,仍然有一個服務器在運行該服務,但是作為服務所有者,您不必擔心該服務器。
For example, AWS Lambda allows you to deploy a “function” to deal with the requests. AWS has a server to run all the functions when they are requested. But you don’t need to worry about how this server works or how to make your code work with this server. All you need to know is that you write a function then push it to the Lambda service.
例如,AWS Lambda允許您部署“功能”來處理請求。 AWS擁??有一臺服務器,可以在需要時運行所有功能。 但是您不必擔心該服務器的工作方式或如何使代碼與此服務器一起工作。 您需要知道的是編寫一個函數,然后將其推送到Lambda服務。
And the sweetest part is that it’s very cheap. Amazon Lambda provides 1M free requests and 400,000 GB-seconds free compute time per month (which means your computation can use 1GB memory for 400,000 seconds), which is enough for most small services. Compared to EC2, where a nano instance would cost you $0.0058 per Hour (which is $0.14 per day), Lambda is way cheaper.
最甜蜜的部分是它非常便宜。 Amazon Lambda每月提供1M的免費請求和400,000 GB-秒的免費計算時間(這意味著您的計算可以使用1GB內存持續400,000秒),足以滿足大多數小型服務的需求。 與EC2相比,納米實例的價格為每小時0.0058美元(每天0.14美元),而Lambda便宜得多。
我們將在這里做什么 (What we’ll do here)
In this post, I will show you how to build a small serverless personal website using AWS. The website has the following characteristics:
在本文中,我將向您展示如何使用AWS構建小型無服務器個人網站。 該網站具有以下特點:
- Includes both front-end and back-end 包括前端和后端
- Mostly static, or front-end heavy 通常是靜態的,或者前端很重
- API requests — these are rare but necessary API請求-很少但有必要
- Back-end does not require too much memory or CPU (for example, a simple web counter that only requires one DB access) 后端不需要太多的內存或CPU(例如,僅需要一個DB訪問權限的簡單Web計數器)
Our service will be deployed at the following domains (I used fake domains in this post):
我們的服務將部署在以下域中(我在這篇文章中使用了虛假域):
API Service:
https://myservice-api.example.com
API服務:
https://myservice-api.example.com
:https://myservice-api.example.com
Front End:
https://myfrontend.example.com
前端:
https://myfrontend.example.com
:https://myfrontend.example.com
A serverless solution is perfect both technically and from a cost point of view. We will use the following AWS services:
從技術和成本角度來看,無服務器解決方案都是完美的。 我們將使用以下AWS服務:
- Lambda + API Gateway + S3, for API server Lambda + API Gateway + S3,用于API服務器
- DynamoDB, for data storage DynamoDB,用于數據存儲
- S3, for static web hosting S3,用于靜態虛擬主機
- Cloudfront, for distributed CDN Cloudfront,用于分布式CDN
- AWS Certificate Manager (ACM), for generating certificates for our https website AWS Certificate Manager(ACM),用于為我們的https網站生成證書
For the API server, we will use a Python + Flask combination, and Zappa as the serverless toolkit.
對于API服務器,我們將使用Python + Flask組合以及Zappa作為無服務器工具箱。
設置AWS環境 (Setting up the AWS Environment)
First we need to set up the AWS environment so that we can access AWS from our code and zappa. This takes two steps:
首先,我們需要設置AWS環境,以便可以從代碼和zappa訪問AWS。 這需要兩個步驟:
- We need to create an AWS user for programmatic access 我們需要創建一個AWS用戶以進行編程訪問
- We need to set up a local AWS environment to use for that user 我們需要設置一個本地AWS環境以供該用戶使用
創建一個AWS用戶 (Create an AWS User)
Log into AWS, and choose the “IAM” service to manage user credentials.
登錄AWS,然后選擇“ IAM”服務來管理用戶憑證。
Create a user called “myservice-admin”(or any other username you would like to use), and don’t forget to check the “Programmatic access” option.
創建一個名為“ myservice-admin”(或您要使用的任何其他用戶名)的用戶,并且不要忘記選中“ Programmatic access ”選項。
In the next screen, click the “Attach existing policies directly” button, then add “AdministratorAccess” to the user.
在下一個屏幕中,單擊“ 直接附加現有策略 ”按鈕,然后向用戶添加“ AdministratorAccess ”。
Note: From a security perspective this is not the best practice. But for demonstration purposes, this post will not cover the details of narrowing down permissions.
注意:從安全角度來看,這不是最佳實踐。 但是出于演示目的,本文不會涵蓋縮小權限的詳細信息。
Click on the “next” button and then the “Create User” button, and the user myservice-admin
will be created. On the last screen, the Access Key ID and Secret access key are displayed. Make sure to copy and paste them into a local file. These are the API credentials we are going to use in the next step.
單擊“下一步”按鈕,然后單擊“創建用戶”按鈕,將創建用戶myservice-admin
。 在最后一個屏幕上,顯示訪問密鑰ID和秘密訪問密鑰 。 確保將它們復制并粘貼到本地文件中。 這些是我們將在下一步中使用的API憑據。
Note: This is the only place you can view the secret access keys! If you fail to make a copy of them, you have to go to the user detail screen and generate a new pair of access keys and secret.
注意: 這是您可以查看秘密訪問密鑰的唯一位置 ! 如果您無法復制它們,則必須轉到用戶詳細信息屏幕并生成一對新的訪問密鑰和密碼。
設置您的本地AWS環境 (Setup your Local AWS Environment)
We need to create a local environment in order to use AWS locally.
我們需要創建一個本地環境才能在本地使用AWS。
First, let’s install the awscli
tool, which will help us configure the environment:
首先,讓我們安裝awscli
工具,它將幫助我們配置環境:
$ sudo apt install awscli
After installation, we will setup AWS by using the aws configure
command:
安裝后,我們將使用aws configure
命令設置AWS:
$ aws configureAWS Access Key ID [None]: ******AWS Secret Access Key [None]: ******Default region name [None]: us-east-1Default output format [None]: json
Here we need to type in the Access Key ID and Secret Access Key we received from the last step. In terms of default region, I used us-east-1
. You can choose any region you like, but other regions may cause some trouble when setting up CloudFront.
在這里,我們需要輸入從上一步收到的訪問密鑰ID和秘密訪問密鑰 。 在默認區域方面,我使用了us-east-1
。 您可以選擇自己喜歡的任何區域,但是其他區域在設置CloudFront時可能會造成一些麻煩。
在DynamoDB中創建表 (Create a Table in DynamoDB)
In order to store the website visitor counter value in DynamoDB, we need a persistent store. So we need to create a table and populate an initial value within it.
為了將網站訪問者計數器值存儲在DynamoDB中,我們需要一個持久存儲。 因此,我們需要創建一個表并在其中填充一個初始值。
Within the AWS console, choose DynamoDB service. Then click the “Create Table” button. In the “Create DynamoDB table” screen, fill the Table name with myservice-dev
and the Primary key field with id
, then click the Create Table button.
在AWS控制臺中,選擇DynamoDB服務。 然后點擊“ 創建表格 ”按鈕。 在“創建DynamoDB表”屏幕中,在表名稱中填充myservice-dev
,在主鍵字段中填充id
,然后單擊“ 創建表”按鈕。
After a couple of seconds, the table should be created. Select the newly created table, choose the Items tab from the right pane, then click the Create item button, and create an item with id='counter'
and counter_value=0
.
幾秒鐘后,應該創建該表。 選擇新創建的表,從右窗格中選擇“ 項目”選項卡,然后單擊“ 創建項目”按鈕,然后創建一個id='counter'
和counter_value=0
。
Note: You need to click the plus sign on the left side to add the
counter_value
attribute, and don’t forget to set the type ofcounter_value
to Number.注意:您需要單擊左側的加號以添加
counter_value
屬性,并且不要忘記將counter_value
的類型設置為Number 。
創建一個API服務 (Create an API Service)
Next, we’ll create the API service. For demonstration purposes, this API service will provide a counter API which will increase a counter value when clicked. The counter value will be stored in DynamoDB. The API endpoints are:
接下來,我們將創建API服務。 出于演示目的,此API服務將提供一個計數器API,當單擊該計數器API時會增加計數器值。 計數器值將存儲在DynamoDB中。 API端點是:
POST /counter/increase
increases the counter and returns the counter valuePOST /counter/increase
增加計數器并返回計數器值GET /counter
returns the current counter valueGET /counter
返回當前計數器值
用Python和Flask編碼API服務 (Coding the API Service with Python and Flask)
We will start with creating a Python virtual environment and install the necessary packages:
我們將從創建Python虛擬環境開始并安裝必要的軟件包:
$ mkdir myservice && cd myservice$ python3 -m venv .env$ source .env/bin/activate(.env)$ pip install flask boto3 simplejson
flask
is the web framework and the boto3
package is required for accessing DynamoDB. simplejson
can help us deal with some JSON conversion issues. Let’s create the service by creating a file myservice.py
with the content below:
flask
是Web框架,訪問DynamoDB需要boto3
軟件包。 simplejson
可以幫助我們處理一些JSON轉換問題。 讓我們通過創建文件myservice.py
來創建服務,其內容如下:
import boto3from flask import Flask, jsonify
app = Flask(__name__)
# Initialize dynamodb accessdynamodb = boto3.resource('dynamodb')db = dynamodb.Table('myservice-dev')
@app.route('/counter', methods=['GET'])def counter_get(): res = db.get_item(Key={'id': 'counter'}) return jsonify({'counter': res['Item']['counter_value']})
@app.route('/counter/increase', methods=['POST'])def counter_increase(): res = db.get_item(Key={'id': 'counter'}) value = res['Item']['counter_value'] + 1 res = db.update_item( Key={'id': 'counter'}, UpdateExpression='set counter_value=:value', ExpressionAttributeValues={':value': value}, ) return jsonify({'counter': value})
Create a run.py
file to test this API service locally:
創建一個run.py
文件以在本地測試此API服務:
from myservice import appif __name__ == '__main__': app.run(debug=True, host='127.0.0.1', port=8000)
Now run the service:
現在運行服務:
(.env)$ python run.py
And we can test this service with the following commands (open another terminal to type these commands):
我們可以使用以下命令測試該服務(打開另一個終端以鍵入這些命令):
$ curl localhost:8000/counter{ "counter": 0}$ curl -X POST localhost:8000/counter/increase{ "counter": 1}$ curl -X POST localhost:8000/counter/increase{ "counter": 2}$ curl localhost:8000/counter{ "counter": 2}
We can see that our code is working and it is successfully increasing the counter!
我們可以看到我們的代碼正在運行,并且正在成功增加計數器!
使用Zappa將我們的代碼部署到Lambda (Deploying our code to Lambda with Zappa)
Deploying our API to Lambda is extremely easy with zappa. First, we need to install zappa:
使用zappa,將我們的API部署到Lambda非常容易。 首先,我們需要安裝zappa:
(.env)$ pip install zappa
Then initialize the zappa environment with zappa init
. It will ask you some questions, but generally you can use default answers for all the questions:
然后使用zappa init
初始化zappa環境。 它會問您一些問題,但是通常您可以對所有問題使用默認答案:
(.env)$ zappa init...What do you want to call this environment (default 'dev'): ...What do you want to call your bucket? (default 'zappa-ab7dd70x5'):
It looks like this is a Flask application.What's the modular path to your app's function?This will likely be something like 'your_module.app'.We discovered: myservice.appWhere is your app's function? (default 'myservice.app'): ...
Would you like to deploy this application globally? (default 'n') [y/n/(p)rimary]:
Okay, here's your zappa_settings.json:
{ "dev": { "app_function": "myservice.app", "aws_region": "us-east-1", "profile_name": "default", "project_name": "myservice", "runtime": "python3.6", "s3_bucket": "zappa-ab7dd70x5" }}
Does this look okay? (default 'y') [y/n]: ...
After initialization, we can see the generated zappa_settings.json
file. Then we can start to deploy our service:
初始化之后,我們可以看到生成的zappa_settings.json
文件。 然后,我們可以開始部署我們的服務:
(.env)$ zappa deploy devCalling deploy for stage dev.....Deployment complete!: https://2ks1n5nrxh.execute-api.us-east-1.amazonaws.com/dev
Great! Our service is online. You can test this service with curl as well:
大! 我們的服務在線。 您還可以使用curl測試此服務:
(.env)$ curl https://2ks1n5nrxh.execute-api.us-east-1.amazonaws.com/dev/counter{"counter":2}(.env)$ curl -X POST https://2ks1n5nrxh.execute-api.us-east-1.amazonaws.com/dev/counter/increase{"counter":3}(.env)$ curl https://2ks1n5nrxh.execute-api.us-east-1.amazonaws.com/dev/counter{"counter":3}
設置API服務的自定義域 (Setup a Custom Domain for API Service)
However, there is one issue with the API service. The auto generated API endpoint 2ks1n5nrxh.execute-api.us-east-1.amazonaws.com
is very difficult to read or use for human consumption. Fortunately, we can bind a custom domain name to this API endpoint.
但是,API服務存在一個問題。 自動生成的API端點2ks1n5nrxh.execute-api.us-east-1.amazonaws.com
很難閱讀或用于人類消費。 幸運的是,我們可以將自定義域名綁定到該API端點。
We will use the custom domain https://myservice-api.example.com
for this API service. Since we want to serve it with https, we need to get a certificate first. AWS provides a free certificate with the “Certificate Manager” service, and it is very easy to use.
我們將針對此API服務使用自定義域https://myservice-api.example.com
。 由于我們希望通過https進行提供,因此我們需要首先獲得證書。 AWS通過“證書管理器”服務提供了免費證書,并且非常易于使用。
After the certificate is generated, we can use it to setup a custom domain for our service in the AWS API Gateway service.
生成證書后,我們可以使用它為AWS API Gateway服務中的服務設置自定義域。
申請證書 (Apply for a Certificate)
Switch to ACM service in the AWS management console (the service is actually called Certificate Manager, but you can type “ACM” to search for it). Click Request a certificate button, then choose Request a public certificate option in the next screen. The certificate is free as long as you choose a public certificate here.
在AWS管理控制臺中切換到ACM服務(該服務實際上稱為證書管理器,但是您可以鍵入“ ACM”進行搜索)。 單擊請求證書按鈕,然后在下一個屏幕中選擇請求公共證書選項。 該證書是免費的,只要您在此處選擇公共證書即可。
In the next screen, enter the domain name you want to apply the certificate for, then click Next. Here I applied for *.example.com
which means the certificate can be used by all the sub-domains under example.com
. In this way, we can use the same certificate for our front end at myfrontend.example.com
without having to apply for a new one.
在下一個屏幕中,輸入要為其應用證書的域名,然后單擊“ 下一步” 。 我在這里申請了*.example.com
,這意味著證書可以被example.com
下的所有子域使用。 這樣,我們可以在myfrontend.example.com
為前端使用相同的證書,而無需申請新證書。
In the next step, we need to prove that we own this domain name. Since I applied for this domain name from Google Domains, I will choose DNS validation. Click the Review button then click Confirm and Request.
下一步,我們需要證明我們擁有此域名。 由于我是從Google Domains申請此域名的,因此我將選擇DNS驗證 。 單擊“ 審閱”按鈕,然后單擊“ 確認并請求” 。
The certificate request will be created, and a validation screen will be displayed. The instructions show how to validate this domain name:
將創建證書申請,并顯示驗證屏幕。 說明說明如何驗證此域名:
Based on the instructions, we need to add a CNAME
record and assign it the given value. In my case, I will open Google Domains, find my domain name example.com
, and add the specified CNAME record:
根據說明,我們需要添加一個CNAME
記錄并為其指定值。 就我而言,我將打開Goog??le Domains,找到我的域名example.com
,并添加指定的CNAME記錄:
Note: I only added the random string _2adee19a0967c7dd5014b81110387d11
in the Name field, without typing the .example.com
part. This is to avoid the suffix .example.com
part getting duplicated.
注意:我只在“名稱”字段中添加了隨機字符串_2adee19a0967c7dd5014b81110387d11
,而沒有鍵入.example.com
部分。 這是為了避免后綴.example.com
部分重復。
Now, we need to wait for about 10 minutes until AWS Certificate Manager validates this domain name. Once validated, the “Status” column in the certificate will display “Issued” in green.
現在,我們需要等待大約10分鐘,直到AWS Certificate Manager驗證該域名。 驗證后,證書中的“狀態”列將以綠色顯示“已發行”。
Now that we have the certificate ready, we can start binding our custom domain name to our API.
現在我們已經準備好證書,我們可以開始將自定義域名綁定到我們的API。
為我們的API服務設置自定義域 (Setuping up a Custom Domain for our API Service)
Go to the “API Gateway” service. From the “APIs” in the left pane, we can see that our API myservice-dev
has already been created by zappa.
轉到“ API網關”服務。 從左窗格中的“ API”,我們可以看到zappa已經創建了我們的API myservice-dev
。
Click on “Custom Domain Names” from the left pane, then click the Create Custom Domain Name button on the right pane and fill in the necessary fields.
在左窗格中單擊“ 自定義域名 ”,然后在右窗格中單擊“ 創建自定義域名”按鈕,并填寫必填字段。
Here I want my API service to be exposed via CloudFront so that it can be accessed with optimal speed all around the world. So I chose Edge Optimized in this configuration. You can choose Regional if you don’t need CloudFront.
在這里,我希望通過CloudFront公開我的API服務,以便可以在全球范圍內以最佳速度對其進行訪問。 因此,我在此配置中選擇“ 邊緣優化” 。 如果不需要CloudFront,則可以選擇“ 區域” 。
Click the “Add mapping” link below, then select our API myservice-dev
as the Destination, and choose dev for the right most box. In this way, our API will not expose the environment name dev
in the URL. Leave the Path field empty.
單擊下面的“ 添加映射 ”鏈接,然后選擇我們的API myservice-dev
作為Destination ,然后在最右邊的框中選擇dev 。 這樣,我們的API將不會在URL中公開環境名稱dev
。 將“ 路徑”字段保留為空。
After clicking the Save button, our custom domain binding will be created. The actual domain binding requires up to 40 minutes to initialize, but we can configure the DNS settings now.
單擊“ 保存”按鈕后,將創建我們的自定義域綁定。 實際的域綁定最多需要40分鐘來初始化,但是我們現在可以配置DNS設置。
From the above screenshot, we can see that the actual domain name is dgt9opldriaup.cloudfront.net
. We need to setup a CNAME
in our DNS, pointing myservice-api.example.com
to the CloudFront subdomain dgt9opldriaup.cloudfront.net
.
從上面的屏幕截圖中,我們可以看到實際的域名是dgt9opldriaup.cloudfront.net
。 我們需要在DNS中設置一個CNAME
,將myservice-api.example.com
指向CloudFront子域dgt9opldriaup.cloudfront.net
。
Go to Google Domains and add the CNAME to the DNS settings:
轉到Google域,然后將CNAME添加到DNS設置中:
After this step, wait for about 40 minutes until the “Initializing…” in the API Gateway service disappears.
完成此步驟后,等待約40分鐘,直到API Gateway服務中的“正在初始化...”消失。
Now try our new API service!
現在嘗試我們的新API服務!
(.env)$ curl https://myservice-api.example.com/counter{"counter":3}(.env)$ curl -X POST https://myservice-api.example.com/counter/increase{"counter":4}(.env)$ curl https://myservice-api.example.com/counter{"counter":4}
前端靜態網站 (Static Website for Front end)
For the next task, we will be creating a front end for our brand new API service. For demonstration purposes, we will create a simple page with a button that triggers the /counter/increase
API call.
對于下一個任務,我們將為我們全新的API服務創建一個前端。 出于演示目的,我們將創建一個帶有觸發/counter/increase
API調用的按鈕的簡單頁面。
編碼前端 (Coding the front end)
Let’s create a new directory called myfrontend
:
讓我們創建一個名為myfrontend
的新目錄:
$ mkdir myfrontend && cd myfrontend
Then make a simple HTML file index.html
:
然后制作一個簡單HTML文件index.html
:
<html><body> <h1>Welcome to my homepage!</h1> <p>Counter: <span id="counter"></span></p> <button id="increase">Increase Counter</button> <script> const setCounter = (counter_value) => { document.querySelector('#counter').innerHTML = counter_value; };
const api = 'https://myservice-api.example.com'; fetch(api + '/counter') .then(res => res.json()) .then(result => setCounter(result.counter));
document.querySelector('#increase') .addEventListener('click', () => { fetch(api + '/counter/increase', { method: 'POST' }) .then(res => res.json()) .then(result => setCounter(result.counter)); } ); </script></body></html>
將前端發布到AWS S3 (Publish the Front end to AWS S3)
To create a static web site with S3, we need to create a bucket with the same name as our domain name.
要使用S3創建靜態網站,我們需要創建一個與域名同名的存儲桶。
Note: If you’ve been following along with this tutorial, the bucket name myfrontend.example.com may not be available, as bucket names are globally unique. Also, you’ll need to create a bucket name based on your public domain. For example,
myfrontend.[yourdomain].com
注意:如果您一直按照本教程進行操作,則存儲桶名稱myfrontend.example.com可能不可用,因為存儲桶名稱是全局唯一的。 另外,您需要根據您的公共域創建存儲桶名稱。 例如,
myfrontend. [yourdomain] .com
myfrontend. [yourdomain] .com
Switch to the S3 service in the AWS management console. Since we want to host the static website on myfrontend.example.com
, we will create a bucket with that name. Click the Create Bucket button, and fill in the bucket name, then keep clicking Next until the bucket is created.
切換到AWS管理控制臺中的S3服務。 由于我們要在myfrontend.example.com
上托管靜態網站, myfrontend.example.com
我們將使用該名稱創建一個存儲桶。 單擊創建存儲桶按鈕,并填寫存儲桶名稱,然后繼續單擊下一步,直到創建存儲桶。
Next, we need to enable static web hosting from this bucket. Open this bucket, then choose the Properties tab, and choose Static Web Hosting. In the dialog, select Use this bucket to host a website, then type index.html
in the “Index document” field. Click Save when finished.
接下來,我們需要從此存儲桶中啟用靜態Web托管。 打開此存儲桶,然后選擇“ 屬性”選項卡,然后選擇“ 靜態虛擬主機” 。 在對話框中,選擇“ 使用此存儲桶托管網站” ,然后在“索引文檔”字段中鍵入index.html
。 完成后單擊“ 保存” 。
Note: The “Endpoint” link shown in the dialog above. We will test our static website with this URL later.
注意:上方對話框中顯示的“端點”鏈接。 我們稍后將使用此URL測試我們的靜態網站。
The last thing we need to do is to enable public access on the bucket. This can be done by adding a bucket policy. Open this bucket and choose the Permissions tab, then click the Bucket Policy button.
我們需要做的最后一件事是在存儲桶上啟用公共訪問。 這可以通過添加存儲桶策略來完成。 打開此存儲桶,然后選擇“ 權限”選項卡,然后單擊“ 存儲桶策略”按鈕。
Type in the following content as the policy, then click the Save button (don’t forget to replace myservice.example.com
with your domain name).
輸入以下內容作為策略,然后單擊“ 保存”按鈕(不要忘記用您的域名替換myservice.example.com
)。
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::myfrontend.example.com/*" } ]}
After saving, we should be able to see an orange “public” sign on the Bucket Policy button and the Permissions tab, which indicates that our bucket is publicly accessible.
保存后,我們應該能夠在“ 存儲桶策略”按鈕和“ 權限”選項卡上看到一個橙色的“公共”符號,這表明我們的存儲桶可以公開訪問。
Now the bucket is created but it is still empty. We need to upload our front end code files to this bucket. Make sure we are in the newly created myfrontend
directory and type the following command:
現在創建了存儲桶,但它仍然是空的。 我們需要將前端代碼文件上傳到此存儲桶。 確保我們位于新創建的myfrontend
目錄中,然后鍵入以下命令:
# Make sure you are in the `myfrontend` directory...$ aws s3 sync . s3://myfrontend.example.com
The above command copies all files fromt he current .
directory to S3.
上面的命令從當前復制所有文件.
目錄到S3。
All done! Now we can test this static web site with the URL displayed earlier. Open that URL with any browser (in my case, http://myfrontend.example.com.s3-website-us-east-1.amazonaws.com/) and see the result!
全做完了! 現在,我們可以使用前面顯示的URL測試此靜態網站。 使用任何瀏覽器(在我的情況下為http://myfrontend.example.com.s3-website-us-east-1.amazonaws.com/)打開該URL,然后查看結果!
Oops! The counter is not displayed at all. ?
糟糕! 計數器完全不顯示。 ?
And it looks like we got some JavaScript error. We can see the following error in the console:
看來我們遇到了一些JavaScript錯誤。 我們可以在控制臺中看到以下錯誤:
Failed to load https://myservice-api.example.com/counter: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myfrontend.example.com.s3-website-us-east-1.amazonaws.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Apparently we need to set the CORS header in order to make this script work, since the backend API is located on another domain. But since we’re going to set up a custom domain for the frontend, the URL will change, so we will worry about CORS later.
顯然,我們需要設置CORS標頭以使此腳本起作用,因為后端API位于另一個域上。 但是,由于我們將為前端設置自定義域,因此URL將會更改,因此我們稍后會擔心CORS。
為我們的靜態網站設置CloudFront (Setting up CloudFront for our Static Web site)
The last step is to setup CloudFront for our front end. Since we have already created a certificate for *.example.com
, this step will be very easy.
最后一步是為我們的前端設置CloudFront。 由于我們已經為*.example.com
創建了證書,因此此步驟將非常容易。
Switch to CloudFront service in the AWS management console. Click Create Distribution button, then click the Start button in the “Web” section.
在AWS管理控制臺中切換到CloudFront服務。 單擊創建分發按鈕,然后單擊“ Web”部分中的開始按鈕。
In the “Create Distribution” screen, we need to make five changes:
在“創建分發”屏幕中,我們需要進行五項更改:
Click the Origin domain name input box and select our S3 bucket
myfrontend.example.com.s3.amazonaws.com
.點擊原始域名輸入框,然后選擇我們的S3存儲桶
myfrontend.example.com.s3.amazonaws.com
。Then change the Viewer Protocol Policy to “Redirect HTTP to HTTPS” in order to force https access.
然后將查看器協議策略更改為“將HTTP重定向到HTTPS”,以強制進行https訪問。
In the Alternate Domain Names box, type in our custom domain. In this case we type in
myfrontend.example.com
.在“ 備用域名”框中,鍵入我們的自定義域。 在這種情況下,我們輸入
myfrontend.example.com
。Scroll down to the SSL Certificate section, choose “Custom SSL Certificate”, then select our
*.example.com
certificate.向下滾動到SSL證書部分,選擇“自定義SSL證書”,然后選擇我們的
*.example.com
證書。Change Default Root Object to
index.html
.將默認根對象更改為
index.html
。
After the distribution is created, we can see the CloudFront domain in the distribution list.
創建分配后,我們可以在分配列表中看到CloudFront域。
Although the status is still “In Progress”, we can setup our DNS record now. Go to Google Domains and add a CNAME for this domain:
盡管狀態仍為“進行中”,但我們現在可以設置DNS記錄。 轉到Google域,并為此域添加一個CNAME:
Then wait until the distribution status change to “Deployed”. Now open your browser and try to access myfrontend.example.com
. We can see the exact same static web site!
然后等待,直到分發狀態更改為“已部署”。 現在打開瀏覽器,嘗試訪問myfrontend.example.com
。 我們可以看到完全相同的靜態網站!
解決CORS問題 (Fix the CORS issue)
Now the only issue left is CORS. Since we are using a different domain name on the backend and frontend, we need to add CORS support.
現在剩下的唯一問題是CORS。 由于我們在后端和前端使用了不同的域名,因此我們需要添加CORS支持。
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. — Wikipedia
跨域資源共享(CORS)是一種機制,它允許從提供第一資源的域之外的另一個域請求網頁上的受限資源(例如,字體)。 — 維基百科
Go back to our API directory (myservice
) and activate the Python environment. Then install the flask_cors
package.
返回我們的API目錄( myservice
)并激活Python環境。 然后安裝flask_cors
軟件包。
$ cd myservice$ source .env/bin/activate(.env)$ pip install flask_cors
Then edit myservice.py
and add the following lines (in bold):
然后編輯myservice.py
并添加以下幾行(粗體):
import boto3from flask import Flask, jsonifyfrom flask_cors import CORS
app = Flask(__name__)CORS(app, origins=['https://myfrontend.example.com'])
Push the updated service to AWS Lambda:
將更新的服務推送到AWS Lambda:
(.env)$ zappa update dev
Now try to refresh our browser. We can see the counter is displayed correctly. Clicking the “Increase Counter” button can increase the counter as well.
現在嘗試刷新我們的瀏覽器。 我們可以看到計數器顯示正確。 單擊“增加計數器”按鈕也可以增加計數器。
結論 (Conclusion)
In this post we explored various AWS services required to create a simple serverless service. You may feel there are too many AWS services if you are not familiar with AWS, but most AWS services we used here are for one-time use. Once they are setup, we don’t need to touch them at all in further development. All you need to do is to run zappa update
and aws s3 sync
.
在本文中,我們探討了創建簡單的無服務器服務所需的各種AWS服務。 如果您不熟悉AWS,您可能會覺得AWS服務太多,但是我們在這里使用的大多數AWS服務都是一次性的。 設置好之后,我們就無需再進一步開發了。 您所需要做的就是運行zappa update
和aws s3 sync
。
Besides, this is way easier than setting up a private VPS, installing web servers, and writing a Jenkins job for continuous deployment.
此外,這比設置私有VPS,安裝Web服務器以及編寫Jenkins作業進行連續部署要容易得多。
As a summary, here are the key takeaways from this post:
總結一下,這是這篇文章的主要內容:
- Lambda can run a simple service. This service can be exposed by API Gateway. Lambda可以運行簡單的服務。 可以通過API網關公開此服務。
- zappa is a great tool if you want to write serverless services in Python. 如果您想用Python編寫無服務器服務,那么zappa是一個很棒的工具。
- S3 bucket can be used for static hosting. S3存儲桶可用于靜態托管。
- Apply for a certificate from AWS ACM if you want to use https. 如果要使用https,請從AWS ACM申請證書。
- API Gateway and CloudFront both support custom domain names. API Gateway和CloudFront都支持自定義域名。
Hope you like this post and don’t hesitate to clap ? for me if you did! Follow me if you want to read more about web development.
希望您喜歡這篇文章,不要猶豫拍手嗎? 對我來說,如果你做到了! 如果您想了解有關Web開發的更多信息,請關注我。
翻譯自: https://www.freecodecamp.org/news/how-to-create-a-serverless-service-in-15-minutes-b63af8c892e5/
服務器創建多個dhcp服務