Flask + Redis + Docker-compose 快速搭建与上线简易版网络服务
案例来自于官方文档,后由自我优化编写,更轻量、便捷、快速此项目
请确保docker,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)
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
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
在后面增加了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 上同
FROM python:3.7-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
挂载
version: "3.8"
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
redis:
image: "redis:alpine"
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有