Lesson 9. Deploy 1. Deploy Backend
Let's start with the backend deploy.
We use Serverless framework.
> npm i serverless-lambda-nestjs> npm i -D serverless serverless-layers @types/aws-lambda
apps/hero-api/src/main.ts
import { Logger } from '@nestjs/common'import { NestFactory } from '@nestjs/core'import { APIGatewayProxyHandler } from 'aws-lambda'import { ServerlessNestjsApplicationFactory } from 'serverless-lambda-nestjs'import { AppModule } from './app/app.module'const globalPrefix = 'api'export async function bootstrap() {const app = await NestFactory.create(AppModule)app.setGlobalPrefix('api')const port = process.env.PORT || 3333await app.listen(port, () => {Logger.log('Listening at http://localhost:' + port + '/' + globalPrefix)})}// Run Nestjs application locallyif (process.env.NX_CLI_SET) {bootstrap()}// Run Nestjs application in AWS Lambdaexport const handler: APIGatewayProxyHandler = async (event, context) => {const app = new ServerlessNestjsApplicationFactory<AppModule>(AppModule,{// NestFactory.create's option objectcors: {origin: '*',allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',},},(app) => {app.enableCors()app.setGlobalPrefix(globalPrefix)return app})const result = await app.run(event, context)return result}
apps/hero-api/serverless.yml
service: nx-hero-apiframeworkVersion: '>=2.0.0'custom:prune:automatic: truenumber: 3serverless-layers:dependenciesPath: ./apps/hero-api/package.jsonprovider:name: awsruntime: nodejs12.xregion: eu-central-1deploymentBucket: {{bucket-name}}apiGateway:shouldStartNameWithService: trueplugins:- serverless-layerspackage:individually: trueinclude:- dist/apps/hero-api/**exclude:- '**'functions:main:handler: dist/apps/hero-api/main.handlerevents:- http:cors: truepath: '/'method: any- http:cors: truepath: '{proxy+}'method: any
apps/hero-api/package.json
{"name": "hero-api","dependencies": {"@nestjs/common": "^7.0.0","@nestjs/core": "^7.0.0","@nestjs/platform-express": "^7.0.0","reflect-metadata": "^0.1.13","rxjs": "~6.6.3","serverless-lambda-nestjs": "0.0.2","tslib": "^2.0.0"},"devDependencies": {}}
> aws s3 mb s3://{{bucket-name}} --region=eu-central-1
workspace.json
..."hero-api": {..."deploy": {"executor": "@nrwl/workspace:run-commands","options": {"parallel": false,"commands": [{"command": "npm run nx run hero-api:build:production"},{"command": "sls deploy --config=apps/hero-api/serverless.yml --stage=prod"}]}}}...
> npm run nx run hero-api:deploy
.gitignore
...# serverless.serverless