Docker

Flask

youngjae5427 2023. 10. 11. 00:20

▶ Flask : python 기반으로 작성된 마이크로 웹 프레임 워크 

                 간단한 웹 사이트나 간단한 API 서버를 만들 수 있음

 

▶ Flask 설치

- nano app.py 생성

ubuntu@ubuntu:~/dockertest$ nano app.py

import time

import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

- nano requirements.txt 생성

ubuntu@ubuntu:~/dockertest$ nano requirements.txt

flask
redis

- nano Dockerfile 생성

ubuntu@ubuntu:~/dockertest$ nano Dockerfile

FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

nano docker-compose.yml  생성 후 docker compose up 실행

version : '3'
services:
  flask:
    image: flask-redis
    ports:
      - 50000:5000
  redis:
    image: redis

▶ 새로 고침 할 때마다 카운터 1씩 증가, 로그도 계속 생성되고 남음

 

▶ 컨테이너를 down -> up 시 카운터가 초기화 되어 다시 1부터 올라감 (db가 저장,연결X)

▶ db 저장되도록 설정 , docker-compose.yml 수정 (포트도 8000번으로 수정)

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"
    volumes:
      - .:/data

 

▶ db가 연결되어 카운터가 down을 해도 지워지지 않고 남아 up시 이어져서 카운터됨 

현재 카운터 8 , docker compose down 진행
접속이 안되는 걸 확인
다시 docker compose up시 카운터가 유지되어 9로 넘어감

'Docker' 카테고리의 다른 글

Docker tomcat 으로 war 배포  (0) 2023.10.12
Windows tomcat 으로 war 배포  (0) 2023.10.12
Wordpress  (0) 2023.10.10
Docker-compose  (0) 2023.10.10
Docker 기본 명령어 (작동)  (0) 2023.10.10