Flask + Redis + Docker-compose 快速搭建与上线简易版网络服务
案例来自于官方文档,后由自我优化编写,更轻量、便捷、快速此项目
请确保docker,docker-compose 能正常运行
实例
构建与运行
- 编写项目
- 环境准备
- 编写业务代码
- 运行测试
- 书写Dockerfile
- 书写docker-compose.yml
- 运行
- 创建服务
- docker-compose build of dockerfile
- 创建网络
- 执行docker-compose
- 项目启动
编写业务代码
# 新建一个项目目录 mkdir -p composetest vim app.py # 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) # Esc :wq # 书写requirements.txt flask redis
# other app.pyimport timeimport redisfrom 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)if __name__ == "__main__": app.run(host="0.0.0.0", debug=True)
书写Dockerfile
vim Dockerfile # 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"] # Esc :wq
# other Dockerfile FROM python:3.7-alpine ADD . /code WORKDIR /code RUN pip install -r requirements.txt CMD ["python", "app.py"] # Esc :wq
编写docker-compose.yaml
vim docker-compose.yaml# docker-compose.yamlversion: "3.8"services: web: build: . ports: - "5000:5000" redis: image: "redis:alpine" # Esc :wq
# other docker-compose.yaml version: "3.8" services: web: build: . ports: - "5000:5000" volumes: - .:/code redis: image: "redis:alpine"
docker-compose up
docker-compose up
实例优化
业务代码
在后面增加了main函数,这样可以使得我们更便捷与轻量的运行任务
# other 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) if __name__ == "__main__": app.run(host="0.0.0.0", debug=True)
requirements 上同
Dockerfile
FROM python:3.7-alpine ADD . /code WORKDIR /code RUN pip install -r requirements.txt CMD ["python", "app.py"]
docker-compose.yaml
挂载
version: "3.8" services: web: build: . ports: - "5000:5000" volumes: - .:/code redis: image: "redis:alpine"