美文网首页
AWS Serverless——将create-react-ap

AWS Serverless——将create-react-ap

作者: 袁文涛 | 来源:发表于2019-01-17 13:36 被阅读121次

People don't want to buy a quarter-inch drill, they want a quarter-inch hole.

                                                                                       —Theodore Levitt

程序员并不是想买一个EC2,他们只想运行自己的代码。

这就有了serverless。

本文大部分内容引用和翻译来自React官方推荐的博文: Deploying create-react-app to S3 and CloudFront,还有一个第三方网站的资料也很详细:Learn to Build Full-Stack Apps with Serverless and React on AWS.

Prepare

如果你已经考虑到将前端项目部署在S3上,那么这种设计的优点就已无须赘述。

当前React的版本是v16.7.0,建议新建项目,因为不能保证old version可以适配S3。默认管理package的工具是npm,我使用的是yarn,这不影响项目打包运行。

将app build完后将会在build/ 或者dist/目录下得到若干文件和文件夹。

Deploy to S3

默认你已经有了AWS账号,打开控制台,导航至S3

Create bucket

点击`Create bucket`,为你的bucket选择一个合适的名字。然后点击`Create`。

Region这一项可以选择目标客户所在的地理位置,因为后面会用 cloud front做全球CDN加速,所以这一项没那么重要。

点击`Next`,如果你不知道这一页是做什么的,可以跳过继续点击`Next`

在这一页将`Block new public bucket policies `和`Block public and cross-account access if bucket has public policies`这两项反选

点击`Next`后再点击`Create bucket`就可以完成bucket的创建。

enable and configure static website hosting

点击打开你新建的bucket,选中`Properties`标签栏,点击打开`Static website hosting`,选中`Use this bucket to host a website`.

在index document 和Error document中皆填入`index.html`,然后Save。

这个Endpoint就会是你网页的地址。

enable static website

configure bucket policy

选中`Permissions`标签栏,再点击选中`Bucket Policy`,在文字框内输入

{

    "Version": "2012-10-17",

    "Statement": [

        {

            "Sid": "PublicReadForGetBucketObjects",

            "Effect": "Allow",

            "Principal": "*",

            "Action": "s3:GetObject",

            "Resource": "arn:aws:s3:::you-bucket-name/*"

        }

    ]

}

确保resource属性中bucket的名字和你创建的是一致的。

edit bucket policy

点击`Save`.

configure CORS configuration

点击 CORS configuration,输入

<?xml version="1.0" encoding="UTF-8"?>

<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">

<CORSRule>

    <AllowedOrigin>*</AllowedOrigin>

    <AllowedMethod>GET</AllowedMethod>

    <MaxAgeSeconds>3000</MaxAgeSeconds>

    <AllowedHeader>*</AllowedHeader>

</CORSRule>

</CORSConfiguration>

configure CORS configuration

这时候你可以将 build/ 目录下的文件都upload到该bucket下。再去打开`static website hosting`里提供的`endpoint`,就可以看到你的网站。

Deploy to CloudFront

进入Cloud Front,

Create distribution

点击`Create Distribution`,在`Web`下选择`Get Started`

`

然后填入自己项目合适的参数,这是我自己的参数。

Origin Domain Name 这一栏里填入刚刚创建的bucket中static web hosting的endpoint,鼠标选中后也会有提示在下拉栏里。

Default Root Object这一项输入 `index.html`。

一切填写完后点击`Create distribution`。

configure Error Pages

在新建好的 distribution里进入`Error Pages`,然后新建一个`Error Response`主要是让你的项目自己处理一些http status error.

Last

在General 选项中的Domain Name,就是CDN加速后的URL,用Route53处理就好了

相关文章

网友评论

      本文标题:AWS Serverless——将create-react-ap

      本文链接:https://www.haomeiwen.com/subject/cvnbdqtx.html