服務器創建多個dhcp服務_如何在15分鐘內創建無服務器服務

服務器創建多個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.comhttps://myservice-api.example.com

  • Front End: https://myfrontend.example.com

    前端: https://myfrontend.example.comhttps://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。 這需要兩個步驟:

  1. We need to create an AWS user for programmatic access

    我們需要創建一個AWS用戶以進行編程訪問
  2. 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 configurecommand:

安裝后,我們將使用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 of counter_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 value

    POST /counter/increase增加計數器并返回計數器值

  • GET /counter returns the current counter value

    GET /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 updateaws 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服務

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393966.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393966.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393966.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

php snoopy視頻教程,php的Snoopy類

用了兩天這個類&#xff0c;發現很好用。獲取請求網頁里面的所有鏈接&#xff0c;直接使用fetchlinks就可以&#xff0c;獲取所有文本信息使用fetchtext(其內部還是使用正則表達式在進行處理)&#xff0c;還有其它較多的功能&#xff0c;如模擬提交表單等。使用方法&#xff1a…

網頁解析 css

網頁解析 css轉載于:https://www.cnblogs.com/guozepingboke/p/10792298.html

如何看pg數據庫版本號_查看pg數據庫版本

PostgreSQL 基本命令鏈接&#xff1a;http://blog.itpub.net/28602568/viewspace-1841163/標題&#xff1a;PostgreSQL 基本命令作者&#xff1a;&#xff4c;ōττ&#xff52;&#xff59;©版權所有[文章允許轉載,但必須以鏈接方式注明源地址,否則追究法律責任.]安裝步…

leetcode1091. 二進制矩陣中的最短路徑(bfs)

在一個 N N 的方形網格中&#xff0c;每個單元格有兩種狀態&#xff1a;空&#xff08;0&#xff09;或者阻塞&#xff08;1&#xff09;。一條從左上角到右下角、長度為 k 的暢通路徑&#xff0c;由滿足下述條件的單元格 C_1, C_2, ..., C_k 組成&#xff1a;相鄰單元格 C_i …

lock和synchronized的同步區別與選擇

區別如下&#xff1a; 1. lock是一個接口&#xff0c;而synchronized是java的一個關鍵字&#xff0c;synchronized是內置的語言實現&#xff1b;&#xff08;具體實現上的區別在《Java虛擬機》中有講解底層的CAS不同&#xff0c;以前有讀過現在又遺忘了。&#xff09; 2. syn…

首頁顯示登陸用戶名php,首頁登錄后怎么在首頁顯示用戶名以及隱藏登錄框?

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓index.php&#xff1a;登錄頁面用戶名&#xff1a;密碼&#xff1a;沒有賬號&#xff1f;立即注冊——————————————————————————doaction.php&#xff1a;header("Content-type:text/html;charsetutf…

react中使用構建緩存_通過在React中構建Tic Tac Toe來學習ReasonML

react中使用構建緩存3. 7. 2018: UPDATED to ReasonReact v0.4.23. 7. 2018&#xff1a;更新為ReasonReact v0.4.2 You may have heard of Reason before. It’s a syntax on top of OCaml that compiles to both readable JavaScript code and to native and bytecode as well…

echart vue 圖表大小_vue里echarts自適應窗口大小改變

echarts的圖表提供了一個resize方法可以自適應屏幕窗口改變&#xff0c;而重新渲染圖表大小的功能。因此我們只要監聽瀏覽器的窗口改變的resize事件&#xff0c;再結合echarts的圖表&#xff0c;就可以實現我們想要的功能了。如果是單個圖表的情況的話用window.onresize myCha…

用js檢測文本框中輸入的是否符合條件并有錯誤和正確提醒

<!DOCTYPE html> <html><head><meta charset"utf-8"><title>捕獲異常</title></head><script type"text/javascript">function my_func(){try{xdocument.getElementById("input_id").value;ale…

leetcode784. 字母大小寫全排列(回溯)

給定一個字符串S&#xff0c;通過將字符串S中的每個字母轉變大小寫&#xff0c;我們可以獲得一個新的字符串。返回所有可能得到的字符串集合。 示例: 輸入: S “a1b2” 輸出: [“a1b2”, “a1B2”, “A1b2”, “A1B2”] 輸入: S “3z4” 輸出: [“3z4”, “3Z4”] 輸入: S…

Petapoco使用SQLite的異常問題

在DbProviderFactory 初始化時&#xff0c;報一個"System.Data.SQLite.SQLiteFactory”的類型初始值設定項引發異常。 解決&#xff1a;不光要引用System.Data.SQLite。還要把SQLite.Interop.dll添加到運行目錄下。轉載于:https://www.cnblogs.com/crazy29/p/7595552.html…

CPP函數調用的方法

相比于C語言中函數可以直接調用&#xff0c;CPP的函數由于命名存在隱式添加&#xff0c;因此需要通過一套流程才能調用&#xff1a; 1. 編碼中&#xff0c;使用extern "C" 定義一個C函數&#xff0c;返回獲取對象的指針&#xff1b;執行該函數時&#xff0c;獲得一個…

php 算法 二進制文件,關于PHP二進制流 逐bit的低位在前算法(詳解)_PHP教程

復制代碼 代碼如下:/******************************************************* 逐bit的低位在前算法* param $x* return int*/function reverse($x){$result 0;for($i 0; $i < 8; $i){$result ($result <> $i));}return $result & 0xff;}調用展示&#xff1a;…

頂尖科技棋牌游戲開發_如何接受頂尖科技公司的采訪

頂尖科技棋牌游戲開發If you’ve ever wondered how to land an interview with top tech companies or know someone who’s been struggling to get an interview with one, then this article is for you.如果您曾經想過如何與頂尖高科技公司進行面談&#xff0c;或者想知道…

城軌列控系統

關于列控系統想問的問題 1&#xff09;列控系統的組成&#xff1f; 2&#xff09;城軌列控系統和列控系統有哪些區別&#xff1f; 3&#xff09;列控系統的設備圖片&#xff1f; 4&#xff09;列控系統的作用&#xff1f; 1、地鐵的供電部分&#xff1a; 參考&#xff1a;http:…

Thinkphp 發送郵件

TP框架實現發送郵件&#xff0c;親測可用1.在模塊的配置文件config中加入下里面代碼THINK_EMAIL > array(SMTP_HOST > smtp.qq.com, //SMTP服務器SMTP_PORT > 465, //SMTP服務器端口SMTP_USER > 郵箱qq.com, //SMTP服務器用戶名SMTP_PASS > 密碼, //SMTP服務器密…

leetcode40. 組合總和 II(回溯)

給定一個數組 candidates 和一個目標數 target &#xff0c;找出 candidates 中所有可以使數字和為 target 的組合。 candidates 中的每個數字在每個組合中只能使用一次。 說明&#xff1a; 所有數字&#xff08;包括目標數&#xff09;都是正整數。 解集不能包含重復的組合…

python 面部識別_一文教你在Python中打造你自己專屬的面部識別系統

原標題&#xff1a;一文教你在Python中打造你自己專屬的面部識別系統人臉識別是用戶身份驗證的最新趨勢。蘋果推出的新一代iPhone X使用面部識別技術來驗證用戶身份。百度也在使“刷臉”的方式允許員工進入辦公室。對于很多人來說&#xff0c;這些應用程序有一種魔力。但在這篇…

Computer Vision Review Incompletely

機器視覺牛人及其相關領域分類科普轉載于:https://www.cnblogs.com/casperwin/p/6380484.html

php獲取特殊標簽,thinkphp特殊標簽使用

特殊標簽1、比較標簽eq或者 equal 等于neq 或者notequal 不等于gt 大于egt 大于等于lt 小于elt 小于等于heq 恒等于nheq 不恒等于2.范圍標簽in(in namen value9,10,11,12)在這些數字里面(else/)不在這些數字的范圍內(/in)(notin namen value9,10,11,12)在這些數字里面(else/)不…