安装
- 创建项目文件夹
mkdir composetest
cd composetest - 创建一个app.py文件
import time
import redis
from flask import Flask
app = Flask(__name__) #新建一个flask可运行实体
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.
'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
- 创建requirements.txt`
flask
redis
创建Dockerfile
- 创建 Dockerfile 构建 docker镜像,镜像包含python应用的所应用
FROM python:3.4-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
在compose file中定义服务
- 创建一个docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
-- 上述文件中定义了两个服务 web和redis
通过compos创建和运行app
docker-compose up
打开浏览器
https://ap.connect.newegg.net/+CSCOE+/logon.html?a0=15&a1=&a2=&a3=1#form_title_text
参考网址:https://docs.docker.com/compose/gettingstarted/#step-4-build-and-run-your-app-with-compose