본문 바로가기

리눅스

[draft] Serverless Framework를 사용하여 서버리스 애플리케이션을 만드는 방법

Serverless Framework를 사용하여 서버리스 애플리케이션을 만드는 방법

Serverless Framework를 사용하여 "Hello, Serverless!"를 출력하는 간단한 서버리스 애플리케이션을 만드는 방법을 안내해드리겠습니다. 여기서는 AWS Lambda와 API Gateway를 사용하여 HTTP 요청에 대한 응답으로 "Hello, Serverless!"를 반환하는 예제를 보여드리겠습니다.

Serverless Framework 설치

먼저 Node.js 와 npm이 설치되어 있어야 합니다.

이후 아래 명령어로 Serverless Framework를 전역(global)으로 설치합니다.

npm install -g serverless
added 54 packages in 5s

15 packages are looking for funding
  run `npm fund` for details
npm notice
npm notice New minor version of npm available! 10.7.0 -> 10.8.2
npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.8.2
npm notice To update run: npm install -g npm@10.8.2
npm notice

 

npm install -g npm@10.8.2
removed 7 packages, and changed 69 packages in 4s

22 packages are looking for funding
  run `npm fund` for details

Serverless Framework 설치 확인

serverless --version
Serverless ϟ Framework

 • 4.1.12

새 프로젝트 생성

새로운 프로젝트 디렉토리를 만들고 그 안에서 Serverless 서비스를 생성합니다.

mkdir hello-serverless
cd hello-serverless

빈 serverless 서비스를 초기화합니다.

serverless

serverless.yml 설정

serverless.yml 파일은 서버리스 애플리케이션의 핵심 설정 파일입니다.

아래와 같이 수정해줍니다.

vim serverless.yml
service: hello-serverless

provider:
  name: aws
  runtime: nodejs14.x

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
  • service: 프로젝트 이름
  • provider: 사용할 클라우드 제공자(AWS), 런타임(Node.js 14)
  • functions: 배포할 Lambda 함수 정의
  • events: 함수가 트리거되는 이벤트 (여기서는 HTTP GET 요청)

Lambda 함수 작성

이제 실제로 실행될 Lambda 함수를 작성해보겠습니다.

handler.js 파일을 만들고 다음 코드를 추가합니다.

vim handler.js
# handler.js 파일에 다음 내용을 추가
'use strict';

module.exports.hello = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hello, Serverless!',
    }),
  };
};

이 코드는 API Gateway를 통해 /hello 엔드포인트로 들어오는 요청을 받아 JSON 형태의 응답을 반환합니다.

배포(Deploy)

AWS CLI가 설정되어 있다면, 아래 명령으로 바로 배포할 수 있습니다.

serverless deploy

배포가 완료되면 콘솔에 다음과 같은 출력이 나타납니다.

endpoints:
  GET - https://xxxxx.execute-api.ap-northeast-2.amazonaws.com/dev/hello
functions:
  hello: hello-serverless-dev-hello

이제 브라우저나 curl로 해당 URL을 호출해보세요

curl https://xxxxx.execute-api.ap-northeast-2.amazonaws.com/dev/hello
{
  "message": "Hello, Serverless!"
}

 

Serverless Framework를 이용한 첫 서버리스 애플리케이션을 완성했습니다.