Python Flask + Redis 练习

flask-redis

程序准备

准备一个Python文件,名字为 app.py 内容如下:

  1. from flask import Flask
  2. from redis import Redis
  3. import os
  4. import socket
  5. app = Flask(__name__)
  6. redis = Redis(host=os.environ.get('REDIS_HOST', '127.0.0.1'), port=6379)
  7. @app.route('/')
  8. def hello():
  9. redis.incr('hits')
  10. return f"Hello Container World! I have been seen {redis.get('hits').decode('utf-8')} times and my hostname is {socket.gethostname()}.\n"

准备一个Dockerfile

  1. FROM python:3.9.5-slim
  2. RUN pip install flask redis && \
  3. groupadd -r flask && useradd -r -g flask flask && \
  4. mkdir /src && \
  5. chown -R flask:flask /src
  6. USER flask
  7. COPY app.py /src/app.py
  8. WORKDIR /src
  9. ENV FLASK_APP=app.py REDIS_HOST=redis
  10. EXPOSE 5000
  11. CMD ["flask", "run", "-h", "0.0.0.0"]

镜像准备

构建flask镜像,准备一个redis镜像。

  1. $ docker image pull redis
  2. $ docker image build -t flask-demo .
  3. $ docker image ls
  4. REPOSITORY TAG IMAGE ID CREATED SIZE
  5. flask-demo latest 4778411a24c5 About a minute ago 126MB
  6. python 3.9.5-slim c71955050276 8 days ago 115MB
  7. redis latest 08502081bff6 2 weeks ago 105MB

创建一个docker bridge

  1. $ docker network create -d bridge demo-network
  2. 8005f4348c44ffe3cdcbbda165beea2b0cb520179d3745b24e8f9e05a3e6456d
  3. $ docker network ls
  4. NETWORK ID NAME DRIVER SCOPE
  5. 2a464c0b8ec7 bridge bridge local
  6. 8005f4348c44 demo-network bridge local
  7. 80b63f711a37 host host local
  8. fae746a75be1 none null local
  9. $

创建redis container

创建一个叫 redis-server 的container,连到 demo-network上

  1. $ docker container run -d --name redis-server --network demo-network redis
  2. 002800c265020310231d689e6fd35bc084a0fa015e8b0a3174aa2c5e29824c0e
  3. $ docker container ls
  4. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  5. 002800c26502 redis "docker-entrypoint.s…" 4 seconds ago Up 3 seconds 6379/tcp redis-server
  6. $

创建flask container

  1. $ docker container run -d --network demo-network --name flask-demo --env REDIS_HOST=redis-server -p 5000:5000 flask-demo

打开浏览器访问 http://127.0.0.1:5000

应该能看到类似下面的内容,每次刷新页面,计数加1

Hello Container World! I have been seen 36 times and my hostname is 925ecb8d111a.

总结

如果把上面的步骤合并到一起,成为一个部署脚本

  1. # prepare image
  2. docker image pull redis
  3. docker image build -t flask-demo .
  4. # create network
  5. docker network create -d bridge demo-network
  6. # create container
  7. docker container run -d --name redis-server --network demo-network redis
  8. docker container run -d --network demo-network --name flask-demo --env REDIS_HOST=redis-server -p 5000:5000 flask-demo