Serverless Microservices w/ Zappa & Flask

Flask를 이용한 빠른 마이크로서비스 개발, Zappa를 이용한 편리한 서버 구성으로 Serverless Microservices를 구축해본다.

2019년 8월 16일 초안 작성

AWS, 환경

먼저, AWS credentials 파일(~/.aws/credentials)이 존재 해야 한다.

[default]
aws_access_key_id = xxx
aws_secret_access_key = xxxxxx

Zappa를 위한 가상 환경virtual environment을 설치한다. Zappa는 설치된 모든 팩키지를 업로드 하기 때문에 가상 환경으로 분리하여 완전히 독립된 환경으로 구성해야 불필요한 팩키지 까지 업로드 되는 경우가 생기지 않는다.

$ virtualenv .env
$ source .env/bin/activate
$ pip install flask zappa

Flask

Flask의 app.py는 기존과 동일하게 작성한다.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, from Zappa!", 200

# We only need this for local development.
if __name__ == '__main__':
    app.run()

Flask의 실행은 python으로 해도 무방하나, 여기서는 직접 flask를 실행하는 runme.sh를 작성한다. 이 경우 __main__ 코드가 필요하지 않다.

#!/usr/bin/env bash

FLASK=/Users/likejazz/workspace/PycharmProjects/zap/env/bin/flask

sudo FLASK_ENV=development \
    ${FLASK} run \
    --host=0.0.0.0 --port=80

Zappa

로컬에서 충분한 테스트를 거친 후 Zappa로 업로드 한다.

$ zappa init
$ zappa deploy dev
or
$ zappa update dev

이미 업로드 된 상태라면 update 한다. 아래와 같이 업로드가 진행된 후 엔드포인트 URL이 출력된다.

Uploading zap-dev-1565950602.zip (5.8MiB)..
100%|█████████████████████████████████| 6.09M/6.09M [00:01<00:00, 5.49MB/s]
...
Deployment complete!: https://xxx.execute-api.ap-northeast-2.amazonaws.com/dev

업로드된 Zappa 오브젝트는 아래와 같이 조회 가능하다.

$ awless ls buckets
|      ID ▲       |                                       GRANTS            | CREATED |
|-----------------|---------------------------------------------------------|---------|
| zappa-xxx       | FULL_CONTROL[user:xxxx]                                 | 4 mins  |
|                 |                                                         |         |

Templates

Flask 템플릿을 구현할 경우 다음과 같이 templates 디렉토리를 만들어 구성한다. 기존 Flask와 동일하다.

$ tree
.
├── app.py
├── runme.sh
├── templates
│   └── _index.html
└── zappa_settings.json

app.py의 내용은 다음과 같다.

@app.route('/')
def index():
    return render_template('_index.html')

Custom Domains

커스텀 도메인은 이 문서대로 셋팅이 가능하다. 먼저, https를 위한 인증서가 필요하며 Route53을 사용하고 AWS Certificate Manager를 활용하면 CNAME 셋팅을 통한 DNS 인증으로 https 활성화가 가능하다.

인증을 받았다면, 아래와 같이 설정을 추가한다.

{
    "dev": {
        ...
        "certificate_arn": "arn:aws:acm:ap-northeast-2:0996036xxxx:certificate/xxxx-xxxx-xxxx-xxxx",
        "domain": "xxx.yyy.zzz"
    }
}

인증 요청을 한다.

$ zappa certify dev -y
botocore.errorfactory.BadRequestException: An error occurred (BadRequestException) when calling the CreateDomainName operation: Invalid certificate ARN: arn:aws:acm:ap-northeast-2:0996036xxxx:certificate/xxxx-xxxx-xxxx-xxxx. Certificate must be in 'us-east-1'.

us-east-1 인증서

그런데, us-east-1에서 발급된 인증서만 가능하다는 오류가 발생한다. 이는 Amazon API Gateway에서 요구하는 정책이기도 하며, 동일하다. 따라서 인증서를 us-east-1. 즉, N. Virginia에서 발급받아 셋팅한다.

        "certificate_arn": "arn:aws:acm:us-east-1:0996036xxxx:certificate/xxxx-xxxx-xxxx-xxxx",

인증을 다시 시도한다.

$ zappa certify
Calling certify for stage dev..
Are you sure you want to certify? [y/n] y
Certifying domain xxx.yyy.zzz..
Created a new domain name with supplied certificate. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part.
Certificate updated!

성공적으로 셋팅되었으며, 반영되는데 최대 40분 정도 소요된다는 안내가 출력된다. 아울러 Custom Domain은 루트(/)에서만 동작하며, 하위 도메인의 경우 다시 원래대로 Lambda FQDN이 노출된다.

참고

이 문서의 가이드 내용은 Building Serverless Microservices with Zappa and Flask를 참고 했다.

is a collection of Papers I have written.
© 2000 - Sang-Kil Park Except where otherwise noted, content on this site is licensed under a CC BY 4.0.
This site design was brought from Distill.