第一步:新建flask專案 app.py
vim app.py
# 書寫以下內容
from flask import Flask
from redis import Redis
import os
app = Flask(__name__)
redis = Redis(host='redis', port=6379)
@app.route('/')
def hello():
redis.incr('hits')
return '你好! 檢視 %s 次\n' % (redis.get('hits'))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
第二步:編寫Dockerfile
# 用於構建flask專案的映象
vim Dockerfile
# 書寫以下內容
FROM python:3.9
WORKDIR /app
COPY . /app
RUN pip install flask redis -i https://pypi.tuna.tsinghua.edu.cn/simple
EXPOSE 5000
CMD [ "python", "app.py" ]
第三步:編寫docker-compose的yml檔案 docker-compose.yml
vim docker-compose.yml
# 書寫以下內容
version: "3"
services:
redis:
image: redis
web:
build:
context: .
dockerfile: Dockerfile
ports:
- 8080:5000
environment:
REDIS_HOST: redis
第四步:啟動docker-compose
docker-compose up
測試
# 訪問專案
10.0.0.100:8080
# 進入web,ping redis
docker-compose exec web /bin/bash
# 下載ping
apt-get update
apt-get install inetutils-ping
ping redis