서버 인프라/Aws

Typescript를 이용한 어플리케이션 Lambda에 배포하기

트리맨스 2022. 6. 15. 00:26
반응형

 

요즘 lambda가 재밌어 보여서 계속 알아보는 중이다. 람다 (서버리스) 애플리케이션에 대한 설명은 다음 사이트에 잘 나와있다.

https://www.redhat.com/ko/topics/cloud-native-apps/what-is-serverless

 

서버리스란?

서버리스(serverless)란 개발자가 서버를 관리할 필요 없이 애플리케이션을 빌드하고 실행할 수 있도록 하는 클라우드 네이티브 개발 모델입니다.

www.redhat.com

 

간단히 말하면 서버를 관리할 필요가 없는 환경을 말하는데, BaaS (Backend As A Service)환경에서 작동되는 것을 말한다. 즉, 우리는 실행하는 함수만 작성해서 Lambda에 넘겨주면 람다는 구동환경을 알아서 최적화하여 서비스해준다.

 

여튼 Typescript을 이용하여 간단한 Lambda 어플리케이션을 만들어보자.

 

준비하기


먼저 node, npm, serverless cli가 설치되어 있어야 한다.

 

nvm 설치 페이지 (node 버전관리)

https://github.com/nvm-sh/nvm

 

GitHub - nvm-sh/nvm: Node Version Manager - POSIX-compliant bash script to manage multiple active node.js versions

Node Version Manager - POSIX-compliant bash script to manage multiple active node.js versions - GitHub - nvm-sh/nvm: Node Version Manager - POSIX-compliant bash script to manage multiple active nod...

github.com

 

serverless 설치 페이지

https://www.serverless.com/framework/docs/getting-started

 

Setting Up Serverless Framework With AWS

The Serverless Framework documentation for AWS Lambda, API Gateway, EventBridge, DynamoDB and much more.

www.serverless.com

 

폴더 생성 후 serverless 명령어를 입력하면, 알아서 기본 틀을 잘 만들어준다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Creating a new serverless project
 
? What do you want to make? AWS - Node.js - Starter
? What do you want to call this project? test
 
✔ Project successfully created in test folder
 
? Do you want to login/register to Serverless Dashboard? No
 
? Do you want to deploy now? No
 
What next?
Run these commands in the project directory:
 
serverless deploy    Deploy changes
serverless info      View deployed endpoints and resources
serverless invoke    Invoke deployed functions
serverless --help    Discover more commands
cs

 

 

TS 변환


위 작업을 마쳤다면, 다음과 같은 폴더 구조가 나올 것이다.

.gitignore
handler.js
README.md
serverless.yml

 

여기서 여러가지 패키지를 설치해야 한다. 아마존 람다에 배포한다는 가정 하에, 다음과 같은 패키지를 설치한다. 설치 전 npm init으로 npm 환경을 만들자.

npm init
npm install -D typescript serverless-offline serverless-plugin- @types/aws-lambda

 

node_modules 아래에 node 패키지들이 모두 설치되었을 것이다. 순서대로 타입스크립트, 오프라인 실행기, 배포 시 ts 지원, aws-lambda의 타입 패키지들이다. 저들을 devDependency로 설치한다.

 

handler.js 파일을 handler.ts 파일로 변경 후 내용은 다음과 같이 변경한다.

import { Handler, Context } from "aws-lambda";

const hello: Handler = async (event: any, context: Context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: "Hello lambda!",
    }),
  };
};

export { hello };

 

tsconfig.json 파일도 새로 생성한다.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": ["es6", "dom"],
    "moduleResolution": "node",
    "rootDir": "./",
    "sourceMap": true,
    "allowJs": true,
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "noImplicitReturns": true,
    "preserveConstEnums": true,
    "suppressImplicitAnyIndexErrors": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": ["node_modules", "build", "webpack"],
  "types": ["typePatches"]
}

 

그리고 serverless.yml 파일도 수정한다. ts에 관한 플러그인과 핸들러를 약간 수정해야 한다.

service: aws-node-project

frameworkVersion: "3"

plugins:
  - serverless-plugin-typescript
  - serverless-offline

provider:
  name: aws
  runtime: nodejs14.x

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get

 

모두 완성한 이후 콘솔에 serverless offline을 입력하여 구동이 잘 되는지 보다. 아마 localhost:3000/dev/hello로 요청을 보내면 될 것이다. 동작 확인이 끝나면, 이제 배포를 해 보자. 이전에 aws cli가 설치가 잘 되어 있어야 한다.

 

serverless deploy --region <배포할 리전>

 

위 명령어를 입력하면 자동으로 배포를 해 준다. typescript는 알아서 컴파일이 되므로 신경쓸 필요가 없다.

 

 

참고 사이트

https://leonkong.cc/posts/serverless-framework-typescript.html

 

Serverless - TypeScript로 서버리스 프레임워크(Serverless Framework)를 활용한 서버리스 아키텍처 구현

서버리스 프레임워크(Serverless Framework)와 Node를 이용한 TypeScript 서버 만들기 - AWS Lambda 및 API Gateway 활용 TypeScript를 활용하고, Node를 사용하는 서버리스 아키텍처를 서버리스 프레임워크(Serverless Fr

leonkong.cc

 

 

반응형