[AWS] Lambda - Node.js

곽우현·2022년 4월 28일
0

AWS

목록 보기
2/6
post-thumbnail

AWS의 Lambda를 사용하여 Node.js를 배포하는법을 알아보자.
서버리스를 개발할 수 있는 방법은 여러가지가 있다.

  1. AWS Console로 세팅하고 개발 (음 권한문제도 있어 좀 복잡한거같다.)

  2. AWS SAM (Serverless Application Model) : 아직 사용해보지 않았다.

  3. Serverless Framework (npm 모듈인거같다.)

3번째 방법으로 진행했다.

Local에서 AWS 개발환경 세팅

1. aws-cli 가 컴퓨터에 설치되어 있어야 한다. aws-cli 설치방법

2. IAM Access-key 발급

3. AWS configuration 설정

$ aws configure

AWS Access Key ID [None]: 본인 Access key ID
AWS Secret Access Key [None]: 본인 Secret key
Default region name [None]: ap-northeast-2
Default output format [None]: Enter

Node.js 세팅

Spring Boot로도 해봤는데 cold start가 너무 길어서.. Node.js로 하기로 했다.

1. Node.js 설치

각 OS별로 설치해주시면 됩니다.

2. serverless framework 설치

$ npm install -g serverless

3. 프로젝트 폴더 생성 후 index.js, serverless.yml 생성

$ mkdir node-lambda

$ cd node-lambda

$ touch index.js

$ touch serverless.yml

프로젝트 구조

$ tree
.
|-- index.js
`-- serverless.yml

4. serverless.yml 수정

# aws lambda 함수에 생성될 함수 이름중 앞에 붙는 이름
service: node-lambda

# aws 서비스를 사용할거기 때문에 설정, runtime은 document참고
provider:
    name: aws
    runtime: nodejs14.x

# 함수 설정
functions:
	hihi:
      	handler: index.hihi
      	events:
        	- http:
            	path: hipath
            	method: get
            	cors: true

    hello:
      	handler: index.hello
      	events:
        	- http:
            	path: hellpath
            	method: get
            	cors: true

5. index.js 수정

exports.hihi = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

exports.hello = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify('kwakkwakkwak'),
    };
    return response;
}

6. Local 테스트

첫번째 함수 호출
$ serverless invoke local --function hihi
성공적인 결과
{
    "statusCode": 200,
    "body": "\"Hello from Lambda!\""
}
두번째 함수 호출
$ serverless invoke local --function hello
성공적인 결과
{
    "statusCode": 200,
    "body": "\"hello\""
}

7. AWS Lambda 배포

$ serverless deploy --stage local --region ap-northeast-2 --aws-profile default

완료되면 endpoints를 줍니다. curl로 날려보면

$ curl -s https://{가리기}.execute-api.ap-northeast-2.amazonaws.com/dev/hipath
성공적인 결과
"Hello from Lambda!"

참고자료
https://yongyong-blog.tistory.com/1

profile
주니어 Java 개발자

0개의 댓글