AWS의 Lambda
를 사용하여 Node.js
를 배포하는법을 알아보자.
서버리스를 개발할 수 있는 방법은 여러가지가 있다.
AWS Console로 세팅하고 개발 (음 권한문제도 있어 좀 복잡한거같다.)
AWS SAM (Serverless Application Model) : 아직 사용해보지 않았다.
Serverless Framework (npm 모듈인거같다.)
3번째 방법으로 진행했다.
aws-cli
가 컴퓨터에 설치되어 있어야 한다. aws-cli 설치방법$ 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
Spring Boot
로도 해봤는데 cold start가 너무 길어서.. Node.js
로 하기로 했다.
Node.js
설치각 OS별로 설치해주시면 됩니다.
$ npm install -g serverless
index.js
, serverless.yml
생성$ mkdir node-lambda
$ cd node-lambda
$ touch index.js
$ touch serverless.yml
프로젝트 구조
$ tree
.
|-- index.js
`-- serverless.yml
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
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;
}
첫번째 함수 호출
$ serverless invoke local --function hihi
성공적인 결과
{
"statusCode": 200,
"body": "\"Hello from Lambda!\""
}
두번째 함수 호출
$ serverless invoke local --function hello
성공적인 결과
{
"statusCode": 200,
"body": "\"hello\""
}
$ 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!"