小程序几秒钟执行一次
by TJ Holowaychuk
由TJ Holowaychuk
Last year I wrote Blueprints for Up, describing how most of the building blocks are available to create a great serverless experience on AWS with minimal effort. This post talks about the initial alpha release of Up.
去年,我写了《 Up的蓝图》 ,描述了如何利用大多数构建块以最小的努力在AWS上创建出色的无服务器体验。 这篇文章讨论了Up的初始alpha版本。
Why focus on serverless? For starters it’s cost-effective since you pay on-demand, only for what you use. Serverless options are self-healing, as each request is isolated and considered to be “stateless.” And finally it scales indefinitely with ease — there are no machines or clusters to manage. Deploy your code and you’re done.
为什么要专注于无服务器? 对于初学者来说,这是符合成本效益的,因为您仅需按需付费即可使用。 无服务器选项是自我修复的,因为每个请求都是独立的,被认为是“无状态的”。 最后,它可以轻松无限地扩展-没有要管理的机器或集群。 部署代码即可完成。
Roughly a month ago I decided to start working on it over at apex/up, and wrote the first small serverless sample application tj/gh-polls for live SVG GitHub user polls. It worked well and costs less than $1/month to serve millions of polls, so I thought I’d go ahead with the project and see if I can offer open-source and commercial variants.
大约一个月前,我决定在apex / up上开始研究它,并为SVG实时GitHub用户调查编写了第一个小型无服务器示例应用程序tj / gh- polls。 它运行良好,并且为数百万次民意调查提供服务的费用不到1美元/月,所以我认为我会继续进行该项目,看看是否可以提供开源和商业版本。
The long-term goal is to provide a “Bring your own Heroku” of sorts, supporting many platforms. While Platform-as-a-Service is nothing new, the serverless ecosystem is making this kind of program increasingly trivial. This said, AWS and others often suffer in terms of UX due to the flexibility they provide. Up abstracts the complexity away, while still providing you with a virtually ops-free solution.
长期目标是提供一种“带上自己的Heroku”,以支持许多平台。 尽管平台即服务并不是什么新鲜事物,但无服务器生态系统正在使这种程序变得越来越琐碎。 这就是说,AWS和其他服务器由于提供的灵活性而经常遭受用户体验的困扰。 Up消除了复杂性,同时仍然为您提供了几乎无操作的解决方案。
You can install Up with the following command, and view the temporary documentation to get started. Or if you’re sketched out by install scripts, grab a binary release. (Keep in mind that this project is still early on.)
您可以使用以下命令安装Up,并查看临时文档以开始使用。 或者,如果您被安装脚本草绘,请获取二进制发行版 。 (请记住,该项目仍处于早期阶段。)
curl -sfL https://raw.githubusercontent.com/apex/up/master/install.sh | sh
To upgrade to the latest version at any time just run:
要随时升级到最新版本,只需运行:
up upgrade
You may also install via NPM:
您也可以通过NPM安装:
npm install -g up
What features does the early alpha provide? Let’s take a look! Keep in mind that Up is not a hosted service, so you’ll need an AWS account and AWS credentials. If you’re not familiar at all with AWS you may want to hold off until that process is streamlined.
早期Alpha提供哪些功能? 让我们来看看! 请记住,Up不是托管服务,因此您需要一个AWS账户和AWS凭证 。 如果您对AWS一点都不熟悉,则可以推迟到简化该流程之前。
The first question I always get is: how does up(1) differ from apex(1)? Apex focuses on deploying functions, for pipelines and event processing, while Up focuses on apps, apis, and static sites, aka single deployable units. Apex does not provision API Gateway, SSL certs, or DNS for you, nor does it provide URL rewriting, script injection and so on.
我总是得到的第一个问题是:up(1)与apex(1)有何不同? Apex专注于部署功能,用于管道和事件处理,而Up专注于应用程序,api和静态站点(也称为单个可部署单元)。 Apex不为您提供API网关,SSL证书或DNS,也不提供URL重写,脚本注入等。
Up lets you deploy apps, apis, and static sites with a single command. To create an application all you need is a single file, in the case of Node.js, an ./app.js
listening on PORT
which is provided by Up. Note that if you’re using a package.json
Up will detect and utilize the start
and build
scripts.
使用Up,您可以使用单个命令部署应用程序,api和静态站点。 要创建应用程序,您只需要一个文件,就Node.js而言,是一个./app.js
侦听PORT
的./app.js
文件。 请注意,如果您使用的是package.json
Up将检测并利用start
和build
脚本。
const http = require('http')const { PORT = 3000 } = process.env
http.createServer((req, res) => { res.end('Hello World\n')}).listen(PORT)
Additional runtimes are supported out of the box, such as main.go
for Golang, so you can deploy Golang, Python, Crystal, or Node.js applications in seconds.
开箱即main.go
支持其他运行时 ,例如用于Golang的main.go,因此您可以在几秒钟内部署Golang,Python,Crystal或Node.js应用程序。
package main
import ( "fmt" "log" "net/http" "os")
func main() { addr := ":" + os.Getenv("PORT") http.HandleFunc("/", hello) log.Fatal(http.ListenAndServe(addr, nil))}
func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello World from Go")}
To deploy the application type up
to create the resources required, and deploy the application itself. There are no smoke and mirrors here, once it says “complete”, you’re done, the app is immediately available — there is no remote build process.
要部署应用程序类型up
创建所需的资源,并部署应用程序本身。 这里没有烟雾和镜子,一旦它说“完成”,就完成了,该应用程序立即可用-没有远程构建过程。
The subsequent deploys will be even quicker since the stack is already provisioned:
由于已经配置了堆栈,因此后续部署将更加快捷:
Test out your app with up url --open
to view it in the browser, up url --copy
to save the URL to the clipboard, or try it with curl:
使用up url --open
来测试您的应用程序,以在浏览器中查看它,或者使用up url --copy
来将URL保存到剪贴板,或者使用curl进行尝试:
curl `up url`Hello World
To delete the app and its resources just type up stack delete
:
要删除该应用及其资源,只需输入up stack delete
:
Deploy to the staging or production environments using up staging
or up production
, and up url --open production
for example. Note that custom domains are not yet available, they will be shortly. Later you’ll also be able to “promote” a release to other stages.
例如,使用up staging
或up production
以及up url --open production
部署到staging或生产环境。 请注意,自定义域尚不可用, 不久后将可用 。 稍后,您还可以将发行版“推广”到其他阶段。
One feature which makes Up unique is that it doesn’t just simply deploy your code, it places a Golang reverse proxy in front of your application. This provides many features such as URL rewriting, redirection, script injection and more, which we’ll look at further in the post.
使Up独特的一项功能是它不仅可以简单地部署代码,还可以在应用程序的前面放置一个Golang反向代理。 这提供了许多功能,例如URL重写,重定向,脚本注入等,我们将在后续文章中进一步介绍。
Up follows modern best practices in terms of configuration, as all changes to the infrastructure can be previewed before applying, and the use of IAM policies can also restrict developer access to prevent mishaps. A side benefit is that it helps self-document your infrastructure as well.
Up在配置方面遵循了现代最佳实践,因为可以在应用之前预览对基础结构的所有更改,并且IAM策略的使用还可以限制开发人员的访问权限,以防止发生意外。 另一个好处是,它还可以帮助您自行记录基础架构。
Here’s an example of configuring some (dummy) DNS records and free SSL certificates via AWS ACM which utilizes LetsEncrypt.
这是通过利用LetsEncrypt的AWS ACM配置一些(虚拟)DNS记录和免费SSL证书的示例。
{ "name": "app", "dns": { "myapp.com": [ { "name": "myapp.com", "type": "A", "ttl": 300, "value": ["35.161.83.243"] }, { "name": "blog.myapp.com", "type": "CNAME", "ttl": 300, "value": ["34.209.172.67"] }, { "name": "api.myapp.com", "type": "A", "ttl": 300, "value": ["54.187.185.18"] } ] }, "certs": [ { "domains": ["myapp.com", "*.myapp.com"] } ]}
When you deploy the application the first time via up
all the permissions required, API Gateway, Lambda function, ACM certs, Route53 DNS records and others are created for you.
当你部署的应用程序通过第一次up
所需的所有权限,API网关,lambda函数,ACM证书,Route53 DNS记录和其他人会为您创建。
ChangeSets are not yet implemented but you will be able to preview further changes with up stack plan
and commit them with up stack apply
, much like you would with Terraform.
ChangeSet尚未实现,但是您将能够使用up stack plan
来预览进一步的更改,并使用up stack apply
提交它们,就像使用Terraform一样。
Check out the configuration documentation for more information.
查看配置文档以获取更多信息。
The regions
array allows you to specify target regions for your app. For example if you’re only interested in a single region you’d use:
regions
数组可让您为应用指定目标区域。 例如,如果您只对单个区域感兴趣,则可以使用:
{ "regions": ["us-west-2"]}
If your customers are concentrated in North America, you may want to use all of the US and CA regions:
如果您的客户集中在北美,则可能要使用所有美国和CA地区:
{ "regions": ["us-*", "ca-*"]}
Lastly of course you can target all 14 regions currently supported:
最后,您当然可以定位当前支持的所有14个地区:
{ "regions": ["*"]}
Multi-region support is still a work-in-progress as a few new AWS features are required to tie things together.
多区域支持仍在进行中,因为需要一些新的AWS功能才能将它们联系在一起。
Up supports static file serving out of the box, with HTTP cache support, so you can use CloudFront or any other CDN in front of your application to dramatically reduce latency.
Up支持开箱即用的静态文件服务,并支持HTTP缓存,因此您可以在应用程序前面使用CloudFront或任何其他CDN来大大减少延迟。
By default the working directory is served (`.`) when type
is “static”, however you may provide a static.dir
as well:
默认情况下,当type
为“ static”时,将为工作目录提供服务(`.`),但是您也可以提供static.dir
:
{ "name": "app", "type": "static", "static": { "dir": "public" }}
The build hooks allow you to define custom actions when deploying or performing other operations. A common example would be to bundle Node.js apps using Webpack or Browserify, greatly reducing the file size, as node_modules is huge.
使用构建挂钩,可以在部署或执行其他操作时定义自定义操作。 一个常见的示例是使用Webpack或Browserify捆绑Node.js应用程序,这大大减小了文件大小,因为node_modules 很大 。
{ "name": "app", "hooks": { "build": "browserify --node server.js > app.js", "clean": "rm app.js" }}
Up allows you to inject scripts and styles, either inline or paths in a declarative manner. It even supports a number of “canned” scripts for Google Analytics and Segment, just copy & paste your write key.
Up允许您以声明的方式插入内联或路径的脚本和样式。 它甚至支持Google Analytics(分析)和Segment的许多“固定”脚本,只需复制并粘贴您的写密钥即可。
{ "name": "site", "type": "static", "inject": { "head": [ { "type": "segment", "value": "API_KEY" }, { "type": "inline style", "file": "/css/primer.css" } ], "body": [ { "type": "script", "value": "/app.js" } ] }}
Up supports redirects and URL rewriting via the redirects
object, which maps path patterns to a new location. If status
is omitted (or 200) then it is a rewrite, otherwise it is a redirect.
Up支持通过redirects
对象进行重定向和URL重写,该对象将路径模式映射到新位置。 如果省略status
(或200),则为重写,否则为重定向。
{ "name": "app", "type": "static", "redirects": { "/blog": { "location": "https://blog.apex.sh/", "status": 301 }, "/docs/:section/guides/:guide": { "location": "/help/:section/:guide", "status": 302 }, "/store/*": { "location": "/shop/:splat" } }}
A common use-case for rewrites is for SPAs (Single Page Apps), where you want to serve the `index.html` file regardless of the path. Unless of course the file exists.
SPA的常见用例是SPA(单页应用),无论路径在哪里,您都希望在其中提供index.html文件。 当然,除非文件存在。
{ "name": "app", "type": "static", "redirects": { "/*": { "location": "/", "status": 200 } }}
If you want to force the rule regardless of a file existing, just add "force": true
.
如果要强制规则而不管文件是否存在,只需添加"force": true
。
Secrets will be in the next release, however for now plain-text environment variables are supported:
机密将在下一发行版中,但是现在支持纯文本环境变量:
{ "name": "api", "environment": { "API_FEATURE_FOO": "1", "API_FEATURE_BAR": "0" }}
The CORS support allows you to to specify which (if any) domains can access your API from the browser. If you wish to allow any site to access your API, just enable it:
通过CORS支持,您可以指定可以从浏览器访问API的域(如果有)。 如果您希望允许任何站点访问您的API,只需启用它:
{ "cors": { "enable": true }}
You can also customize access, for example restricting API access to your front-end or SPA only.
您还可以自定义访问权限,例如,仅将API访问权限限制为您的前端或SPA。
{ "cors": { "allowed_origins": ["https://myapp.com"], "allowed_methods": ["HEAD", "GET", "POST", "PUT", "DELETE"], "allowed_headers": ["Content-Type", "Authorization"] }}
For the low price of $0.5/GB you can utilize CloudWatch logs for structured log querying and tailing. Up implements a custom query language used to improve upon what CloudWatch provides, purpose-built for querying structured JSON logs.
只需$ 0.5 / GB的低价,您就可以利用CloudWatch日志进行结构化日志查询和跟踪。 Up实现了一种自定义查询语言,用于改进CloudWatch提供的内容,该语言专门用于查询结构化JSON日志。
You can query existing logs:
您可以查询现有日志:
up logs
Tail live logs:
尾部实时日志:
up logs -f
Or filter on either of them, for example only showing 200 GET / HEAD requests that take more than 5 milliseconds to complete:
或过滤其中任何一个,例如仅显示200个GET / HEAD请求,这些请求需要5毫秒以上的时间才能完成:
up logs 'method in ("GET", "HEAD") status = 200 duration >= 5'
The query language is quite flexible, here are some more examples from up help logs
查询语言非常灵活,这是up help logs
更多示例
Show logs from the past 5 minutes.$ up logs
Show logs from the past 30 minutes.$ up logs -s 30m
Show logs from the past 5 hours.$ up logs -s 5h
Show live log output.$ up logs -f
Show error logs.$ up logs error
Show error and fatal logs.$ up logs 'error or fatal'
Show non-info logs.$ up logs 'not info'
Show logs with a specific message.$ up logs 'message = "user login"'
Show 200 responses with latency above 150ms.$ up logs 'status = 200 duration > 150'
Show 4xx and 5xx responses.$ up logs 'status >= 400'
Show emails containing @apex.sh.$ up logs 'user.email contains "@apex.sh"'
Show emails ending with @apex.sh.$ up logs 'user.email = "*@apex.sh"'
Show emails starting with tj@.$ up logs 'user.email = "tj@*"'
Show errors from /tobi and /loki$ up logs 'error and (path = "/tobi" or path = "/loki")'
Show the same as above with 'in'$ up logs 'error and path in ("/tobi", "/loki")'
Show logs with a more complex query.$ up logs 'method in ("POST", "PUT") ip = "207.*" status = 200 duration >= 50'
Pipe JSON error logs to the jq tool.$ up logs error | jq
Note that the and
keyword is implied, though you can use it if you prefer.
请注意,暗含and
关键字,尽管您可以根据需要使用它。
This is a property of AWS Lambda as a platform, but the cold start times are typically well below 1 second, and in the future I plan on providing an option to keep them warm.
这是AWS Lambda作为平台的属性,但是冷启动时间通常远低于1秒,并且将来我计划提供一个选项来使其保持温暖。
The up config
command outputs the resolved configuration, complete with defaults and inferred runtime settings – it also serves the dual purpose of validating configuration, as any error will result in exit > 0.
up config
命令输出已解析的配置,包括默认值和推断的运行时设置,它还具有验证配置的双重目的,因为任何错误都会导致exit> 0。
Another benefit of using Up as a reverse proxy is performing crash recovery — restarting your server upon crashes and re-attempting the request before responding to the client with an error.
将Up用作反向代理的另一个好处是执行崩溃恢复-崩溃时重新启动服务器,并在尝试以错误响应客户端之前重新尝试请求。
For example suppose your Node.js application crashes with an uncaught exception due to an intermittent database issue, Up can retry this request before ever responding to the client. Later this behaviour will be more customizable.
例如,假设您的Node.js应用程序由于数据库间歇性问题而崩溃,并且未捕获到异常,那么Up可以在响应客户端之前重试此请求。 稍后,此行为将更加可定制。
It’s hard to call this a feature, but thanks to Golang’s relatively small and isolated binaries, you can install Up in a CI in a second or two.
很难称其为功能,但是由于Golang相对较小且隔离的二进制文件,您可以在一两秒钟内在CI中安装Up。
Up supports HTTP/2 out of the box via API Gateway, reducing the latency for serving apps and sites with with many assets. I’ll do more comprehensive testing against many platforms in the future, but Up’s latency is already favourable:
Up通过API网关开箱即用地支持HTTP / 2,从而减少了为具有许多资产的应用程序和网站提供服务的延迟。 将来,我将在许多平台上进行更全面的测试,但是Up的延迟已经很有利:
Up provides a default error page which you may customize with error_pages
if you’d like to provide a support email or tweak the color.
Up提供了一个默认错误页面,如果您想提供支持电子邮件或调整颜色,则可以使用error_pages
自定义。
{ "name": "site", "type": "static", "error_pages": { "variables": { "support_email": "[email protected]", "color": "#228ae6" } }}
By default it looks like this:
默认情况下,它看起来像这样:
If you’d like to provide custom templates you may create one or more of the following files. The most specific file takes precedence.
如果您想提供自定义模板,则可以创建以下一个或多个文件。 最具体的文件优先。
error.html
– Matches any 4xx or 5xx
error.html
–匹配任何4xx或5xx
5xx.html
– Matches any 5xx error
5xx.html
–匹配任何5xx错误
4xx.html
– Matches any 4xx error
4xx.html
–匹配任何4xx错误
CODE.html
– Matches a specific code such as 404.html
CODE.html
–匹配特定代码,例如404.html
Check out the docs to read more about templating.
查看文档以了解有关模板的更多信息。
So you’ve made it this far, but how well does Up scale? Currently API Gateway and AWS are the target platform, so you’re not required to make any changes in order to scale, just deploy your code and it’s done. You pay only for what you actually use, on-demand, and no manual intervention is required for scaling.
到目前为止,您已经做到了,但是扩展效果如何? 目前,API Gateway和AWS是目标平台,因此不需要进行任何更改即可进行扩展,只需部署代码即可。 您只需按需实际使用的价格付费,而无需人工干预即可进行扩展。
AWS offers 1,000,000 requests per month for free, but you can use http://serverlesscalc.com to plug in your expected traffic. In the future Up will provide additional platforms, so that if one becomes prohibitively expensive, you can migrate to another!
AWS每月免费提供1,000,000个请求,但是您可以使用http://serverlesscalc.com插入您的预期流量。 将来,Up将提供其他平台,因此,如果一个平台的价格过高,您可以迁移到另一个平台!
That’s all for now! It may not look like much, but it’s clocking-in above 10,000 lines of code already, and I’ve just begun development. Take a look at the issue queue for a small look at what to expect in the future, assuming the project becomes sustainable.
目前为止就这样了! 它看起来可能并不多,但是它已经达到了10,000行以上的代码,而我才刚刚开始开发。 假设项目变得可持续,请查看问题队列,以较小的眼光看待将来的期望。
If you find the free version useful please consider donating on OpenCollective, as I do not make any money working on it. I will be working on early access to the Pro version shortly, with a discounted annual price for early adopters. Either the Pro or Enterprise editions will provide the source as well, so internal hotfixes and customizations can be made.
如果您发现免费版本很有用,请考虑在OpenCollective上捐款 ,因为我没有为此而赚钱。 我将致力于早期试用Pro版本,并为早期采用者提供优惠的年度价格。 Pro或Enterprise版本都将提供源代码,因此可以进行内部修补程序和自定义。
Make sure to follow the GitHub repo for updates. Cheers!
确保遵循GitHub存储库进行更新。 干杯!
翻译自: https://www.freecodecamp.org/news/up-b3db1ca930ee/
小程序几秒钟执行一次