无服务器部署
探索将 NestJS 应用部署到 AWS Lambda 或 Google Cloud Functions 等无服务器平台,以低成本实现弹性扩展。
无服务器部署 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 5 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 6 节课。
本课时的部分内容尚未翻译,以英文显示。
Intro to Serverless Deployment
Welcome to serverless deployment! This strategy lets you build and run applications without managing servers.
Instead of provisioning VMs, you write code that runs in response to events, like an HTTP request.
The cloud provider (e.g., AWS, Google Cloud) handles all the server management for you.
Why Serverless for NestJS?
Deploying NestJS on serverless platforms offers compelling advantages, especially for APIs:
- Automatic Scaling: Your application scales instantly with demand, from zero to thousands of requests.
- Cost-Efficiency: You only pay for the compute time consumed by your code, not for idle servers.
- Reduced Operations: No server maintenance, patching, or scaling to worry about. Focus on your code!
Common Serverless Platforms
Several major cloud providers offer robust serverless computing services:
- AWS Lambda: The most popular choice, often used with API Gateway for HTTP endpoints.
- Google Cloud Functions: Google's offering, deeply integrated with the Google Cloud ecosystem.
- Azure Functions: Microsoft's solution for event-driven serverless applications.
We'll primarily focus on concepts applicable to AWS Lambda.
NestJS & Lambda: The Challenge
NestJS applications are typically long-running processes, constantly listening for requests. Serverless functions, however, are designed to be short-lived, executing only when triggered.
The challenge is to make NestJS's robust architecture fit into this 'function-as-a-service' model. We need a way to 'boot up' our NestJS app within the context of a single serverless invocation.
Adapting NestJS for Lambda
To run a NestJS app on AWS Lambda, we use an adapter. This adapter acts as a bridge, translating incoming Lambda events into a format NestJS understands (like an Express.js or Fastify request) and then translating NestJS's response back for Lambda.
Popular tools like @vendia/serverless-express (for Express) or @nestjs/platform-fastify with aws-lambda-fastify help achieve this.
Serverless Framework CLI
The Serverless Framework is a powerful CLI tool that simplifies deploying serverless applications to various providers.
It handles packaging your code, creating cloud resources (like Lambda functions and API Gateway endpoints), and managing deployments.
You can install it globally via npm:
npm install -g serverlessBasic `serverless.yml` Structure
The core of a Serverless Framework project is the serverless.yml file. This YAML configuration defines your service, provider, and functions.
Here's a simplified structure:
service: my-nestjs-api
provider:
name: aws
runtime: nodejs18.x
# ... other AWS configurations
functions:
api:
handler: dist/lambda.handler
events:
- http:
path: /{proxy+}
method: any
cors: trueThe NestJS Lambda Handler
This is the actual entry point for your Lambda function. It initializes your NestJS application and wraps it with an adapter.
The goal is to initialize NestJS only once (a 'warm start') to reduce latency on subsequent calls.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as express from 'express';
import * as serverlessExpress from '@vendia/serverless-express';
let cachedServer;
async function bootstrapServer() {
const expressApp = express();
const adapter = new ExpressAdapter(expressApp);
const app = await NestFactory.create(AppModule, adapter);
await app.init();
return serverlessExpress({ app: expressApp });
}
export const handler = async (event, context) => {
if (!cachedServer) {
cachedServer = await bootstrapServer();
}
return cachedServer(event, context);
};Deploying Your Serverless App
Once your serverless.yml and handler are configured, deploying your NestJS application is straightforward:
- Build: Compile your TypeScript code (e.g.,
npm run build). - Deploy: Run
serverless deployfrom your terminal. The CLI handles packaging and provisioning. - Test: The CLI will output your API Gateway endpoint, which you can use to test your deployed NestJS API.
Serverless Deployment Check
Which of the following are key benefits of deploying a NestJS API on a serverless platform like AWS Lambda?
Recap: Serverless NestJS
In this lesson, we explored how to deploy NestJS applications using serverless platforms like AWS Lambda.
You learned about the benefits (cost, scaling, reduced ops), the challenge of adapting NestJS for short-lived functions, and how the Serverless Framework and adapters help bridge this gap. This approach enables highly scalable and cost-efficient backend services.
常见问题解答
「无服务器部署」课时是免费的吗?
是的 — 「无服务器部署」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 6 节课。
「无服务器部署」这节课中我会学到什么?
探索将 NestJS 应用部署到 AWS Lambda 或 Google Cloud Functions 等无服务器平台,以低成本实现弹性扩展。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NestJS Enterprise Backend APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 5 节课,共 6 节。
「无服务器部署」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?
能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。