用到的三个文件
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 [email protected]" 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都不一样,很方便实现负载均衡
(只是单机实验,生产环境中肯定不是在单机上做负载均衡)