用到的三個文件
docker-compose
version: "3" services: redis: image: redis web: build: context: . dockerfile: Dockerfile environment: REDIS_HOST: redis lb: image: dockercloud/haproxy links: - web ports: - 8080:80 volumes: - /var/run/docker.sock:/var/run/docker.sock
Dockerfile
FROM python:2.7 LABEL maintaner="Peng Xiao xiaoquwl@gmail.com" COPY . /app WORKDIR /app RUN pip install flask redis EXPOSE 80 CMD [ "python", "app.py" ]
app.py
from flask import Flask from redis import Redis import os import socket app = Flask(__name__) redis = Redis(host=os.environ.get('REDIS_HOST', '127.0.0.1'), port=6379) @app.route('/') def hello(): redis.incr('hits') return 'Hello Container World! I have been seen %s times and my hostname is %s.\n' % (redis.get('hits'),socket.gethostname()) if __name__ == "__main__": app.run(host="0.0.0.0", port=80, debug=True)
創建docker-compose的文件夾
mkdir scale
將三個文件上傳進來
rz
執行docker-compose
docker-compose up --scale web=3 -d
瀏覽器輸入宿主ip:8080,報錯如下:Could not find a version that satisfies the requirement Werkzeug>=0.15
顯然pip沒有找到依賴庫的合適版本,升級一下pip,在Dockerfile中修改
RUN pip install flask redis
修改為 RUN python -m pip install --upgrade pip && pip install flask redis
再次執行執行docker-compose
docker-compose up --scale web=3 -d
瀏覽器輸入宿主ip:8080
Hello Container World! I have been seen 5 times and my hostname is 8e5e7d7e796f.
Hello Container World! I have been seen 6 times and my hostname is 5b521b5758a0.
Hello Container World! I have been seen 8 times and my hostname is 03b02d13f35d.
刷新三次,每次的web都不一樣,很方便實現負載均衡
(只是單機實驗,生產環境中肯定不是在單機上做負載均衡)