Serverless Architecture & AWS Lambda로 초기환경 세팅 및 배포하기

손연주·2022년 2월 14일
1

👩🏻‍🎓 AWS Lambda

Serverless Architecture란?

“서버가 없다” 라는 의미가 있지만 사실상 서버가 없는건 아니고 그저 특정 작업을 수행하기 위해서 컴퓨터를 혹은 가상머신에 서버를 설정하고, 이를 통하여 처리하는 것이 아님을 의미한다. 그 대신에, BaaS (Backend as a Service) 혹은 FaaS (Function as a Service) 에 의존하여 작업을 처리하게 된다.

  • BaaS(Backend as a Service) e.g. Firebase, Kinvey ...
  • FaaS(Function as a Service) e.g. AWS Lambda, Azure Functions, Google Cloud Functions ...

FaaS (Function as a Service)

FaaS 는 프로젝트를 여러개의 함수로 쪼개서 (혹은 한개의 함수로 만들어서), 매우 거대하고 분산된 컴퓨팅 자원에 여러분이 준비해둔 함수를 등록하고, 이 함수들이 실행되는 횟수 (그리고 실행된 시간) 만큼 비용을 내는 방식을 말한다.

등록한 함수는 특정 이벤트가 발생했을 때 실행된다.

  • 주기적으로 실행되게끔 설정 할 수 있다. (5분마다, 1시간마다, 하루마다) ⇒ 크롤링 작업에 용이
  • 웹 요청을 처리할 수도 있다. 예를 들어서 특정 URL로 들어오면 어떠한 작업을 하게끔 할 수 있다. 이를 통하여 백엔드 API를 구성 할 수도 있다.
  • 콘솔을 통하여 직접 호출 할 수도 있다.

FaaS vs PaaS

PaaS(Platform as a Service) : 전체 애플리케이션을 배포하여 서버에서 애플리케이션이 24시간동안 계속 돌아가고 있음

FaaS : 애플리케이션이 아닌 함수를 배포하며 계속 실행되고 있는 것이 아닌, 특정 이벤트가 발생 했을 때 실행되고 실행이 되었다가 작업을 마치면 (혹은 최대 타임아웃 시간을 지나면) 종료됨

장점

  1. 비용 : 특정 작업을 하기 위하여 서버를 준비하고 하루종일 켜놓는것이 아니라, 필요할때만 함수가 호출되어 처리되며 함수가 호출된 만큼만 비용이 드므로, 비용이 많이 절약된다.
  2. 인프라 관리 : 네트워크, 장비 이런것들에 대한 구성 작업을 신경 쓸 필요 없다.
  3. 인프라 보안 : 리눅스 업데이트, 최근 발생한 Intel Meltdown 취약점 보안패치, 이런것들 또한 신경 쓸 필요 없다.
  4. 확장성 : 함수가 1초에 1개가 호출되면 1개가 호출되는 것이고, 100,000,00 개가 호출되면 100,000,00 개가 호출되는 것이다. 그리고 호출된 횟수 만큼 돈을 낸다.

단점

  1. 제한 : 모든 코드를 함수로 쪼개서 작업하다보니, 함수에서 사용할 수 있는 자원에 제한이 있다. 하나의 함수가 한 번 호출 될 때, AWS 에서는 최대 1500MB 의 메모리까지 사용 가능하며, 처리시간은 최대 300초까지 사용 가능하다. 때문에, 웹소켓 같이 계속 켜놔야 하는것은 사용하지 못한다. 그 대신에, AWS IoT, Pusher 등의 서비스를 사용할 수 있다.
  2. 로컬 데이터 사용 불가능 : 함수들은 무상태적(stateless)이기 때문에, 데이터를 로컬 스토리지에서 읽고 쓸 수 없다. 하지만 AWS라면 S3, Azure라면 Storage를 이용할 수 있다.

AWS Lambda를 사용하여 Hello world 띄우기 👋🏻

준비 사항

Node.js와 npm

Serverless를 사용하려면, 작업환경에 Node.js(LTS ver) 와 npm이 설치되어있어야 한다. (npm 대신 yarn을 사용해도 무방)

Serverless 설치하기

$ npm install -g serverless
$ sls --version
1.26.0

npm 을 통하여 serverless를 설치하면 serverless 혹은 sls 명령어를 사용할 수 있다.
sls --version 을 입력하여 설치가 잘 됐는지 확인하자.

Serverless 로그인

$ sls login

위 명령어를 통해 로그인 할 수 있고 GitHub 계정으로 로그인 된다.

Serverless 플랫폼에 로그인을 하고 나중에 배포를 하게 된다면, 그동안 배포한 함수와 함수들을 위한 문서들을 확인 할 수 있다.

AWS credentials 설정

$ serverless config credentials --provider aws --key 액세스키ID --secret 비밀액세스키
Serverless: Setting up AWS...
Serverless: Saving your AWS profile in "~/.aws/credentials"...
Serverless: Success! Your AWS access keys were stored under the "default" profile.

Serverless 템플릿을 이용하여 애플리케이션 생성하기

$ sls create -t

다음 명령어를 실행하면 다음과 같이 오류가 뜨면서 사용할 수 있는 템플릿 목록이 나타난다.

Serverless: Generating boilerplate...

  Serverless Error ---------------------------------------

  Template "true" is not supported. Supported templates are: "aws-nodejs", "aws-nodejs-typescript", "aws-nodejs-ecma-script", "aws-python", "aws-python3", "aws-groovy-gradle", "aws-java-maven", "aws-java-gradle", "aws-kotlin-jvm-maven", "aws-kotlin-jvm-gradle", "aws-kotlin-nodejs-gradle", "aws-scala-sbt", "aws-csharp", "aws-fsharp", "aws-go", "aws-go-dep", "azure-nodejs", "google-nodejs", "kubeless-python", "kubeless-nodejs", "openwhisk-nodejs", "openwhisk-php", "openwhisk-python", "openwhisk-swift", "spotinst-nodejs", "spotinst-python", "spotinst-ruby", "spotinst-java8", "webtasks-nodejs", "plugin" and "hello-world".

따라서 사용하고 싶은 템플릿을 설정할 수 있고, aws-nodejs를 사용한다면

다음 명령어를 입력하면 된다.

$ sls create -t aws-nodejs -p 프로젝트명이름
Serverless: Generating boilerplate...
Serverless: Generating boilerplate in "/Users/yeonjuson/sls-workshop/mail-slack"
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v1.26.0
 -------'

Serverless: Successfully generated boilerplate for template: "aws-nodejs"

그러면, mail-slack 라는 경로에 handler.js파일과 serverless.yml 파일이 나타난다.

함수 호출하기

serverless를 통하여 함수가 잘 작동하는지 확인할 수 있는 방법은 (즉, 함수를 호출 할 때) invoke 를 사용한다.

$ serverless invoke local --function hello
{
    "statusCode": 200,
    "body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":\"\"}"
}

serverless.yml 파일 수정하기

region과 stage를 설정한다. region의 경우엔 AWS에서 배포할 지역을 설정한다. 기본적으로는 미국으로 설정되니, 이 값을 ap-northeast-2 로 입력하여 한국으로 변경한다. stage 는 현재 애플리케이션의 배포 상태를 의미하고 prod 로 하거나, dev로 설정할 수 있다.

추가적으로, hello 함수에서 events 값을 추가하여 API Gatway 와 연결하겠다. 코드 몇 줄이면 함수에 API를 달아줄 수 있다.


service: hello-serverless

provider:
  name: aws
  runtime: nodejs6.10
  stage: dev
  region: ap-northeast-2

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

배포하기

함수를 배포할 때는 sls deploy 명령어를 입력한다.

$ sls deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (409 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..........
Serverless: Stack update finished...
Service Information
service: hello-serverless
stage: dev
region: ap-northeast-2
stack: hello-serverless-dev
api keys:
  None
endpoints:
  GET - https://4mmtbsr9eg.execute-api.ap-northeast-2.amazonaws.com/dev/hello
functions:
  hello: hello-serverless-dev-hello
Serverless: Publish service to Serverless Platform...
Service successfully published! Your service details are available at:
https://platform.serverless.com/services/velopert/hello-serverless

AWS Lambda에서 확인하기

AWS Lambda → 애플리케이션 에서 배포 상태를 확인할 수 있다.

serverless offline

여기까지가 초기환경 세팅 후 배포하는 과정이었고, 실제로 코드를 작성 후에 배포를 한다고 생각해 보자. 그렇다면 함수를 수정할 때마다 또 sls deploy 과정을 거치고 실제로 배포가 될 때까지 기다리고 다시 테스트, 수정->deploy->테스트->수정...을 반복하기가 시간상 큰 손해다. 로컬에서 테스트를 위해 serverless offline으로 진행한다.

$ yarn add serverless-offline --save-dev

serverless.yml

plugins:
  - serverless-offline

$ sls offline

$ sls offline
Compiling with Typescript...
Using local tsconfig.json - tsconfig.json
Typescript compiled.
Watching typescript files...

Starting Offline at stage dev (ap-northeast-2)

Offline [http for lambda] listening on http://localhost:3002
Function names exposed for local invocation by aws-sdk:
           * mail-slack: datahunt-mail-slack-dev-mail-slack

   ┌──────────────────────────────────────────────────────────────────────────────┐
   │                                                                              │
   │   POST | http://localhost:3000/v1/contacts                                   │
   │   POST | http://localhost:3000/2015-03-31/functions/mail-slack/invocations   │
   │                                                                              │
   └──────────────────────────────────────────────────────────────────────────────┘

Server ready: http://localhost:3000 🚀

Enter "rp" to replay the last request

그럼 test할 수 있는 url 주소가 나오고, postman을 이용해 테스트를 하면 된다. invoke로 테스트할 수 있는 방법은 공식문서에 나와있다.

serverless.yml 설정

테스트를 완료했다면 배포를 진행한다.
serverless.yml 파일 설정이 중요하다.

--------------------------------------------------------작성 중

plugins

1. serverless-ignore

2. serverless-offline

위에서 언급했듯 로컬에서의 테스트를 위해 사용한다.

3. serverless-plugin-typescript

4. serverless-dotenv-plugin

serverless-dotenv-plugin 설치하는데 npm으로만 설치할 수 있어서 이 부분에서 부득이하게 yarn을 삭제하고 npm으로 변경하였다.

provider

functions

배포 log 확인

  1. AWS Lambda 접속
  2. 애플리케이션 선택
  3. 리소스에서 해당 함수 선택
  4. 모니터링 선택
  5. CloudWatch에서 로그 보기 선택

참고

profile
할 수 있다는 생각이 정말 나를 할 수 있게 만들어준다.

0개의 댓글