6.4 水平扩展和负载均衡

思过崖

配置修改

flask-redis 的 compose

version: "3"
services:
  redis:
    image: redis
  web:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 5000:5000
    environment:
      REDIS_HOST: redis

去掉ports之后改为如下:

version: "3"
services:
  redis:
    image: redis

  web:
    build:
      context: .
      dockerfile: Dockerfile

    environment:
      REDIS_HOST: redis

就可以动态的扩展web容器的数量了

如果不去掉的话会报错,一个虚拟机的端口不可能映射多个容器的端口

水平扩展

# 默认会启1台web容器
docker-compose up -d

# 此时会增加9台,变为10台
docker-compose up --scale web=10 -d

# 此时会删除5台,变为5台
docker-compose up --scale web=5 -d

负载均衡

docker-compose.yml

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 hub.c.163.com/library/python
LABEL maintainer="924714558@qq.com"
COPY . /app
WORKDIR /app
RUN pip install flask redis
EXPOSE 80
CMD ["python","app.py"]

app.py

import os
import socket

from flask import Flask
from redis import Redis

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 'hostname is %s and hits %s times' % (socket.gethostname(),redis.get('hits'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)

使用如下命令测试即可

docker-compose up -d
docker-compose up --scale web=5 -d
curl http://127.0.0.1:8080
hostname is 417fc5a4f3a3 and hits b'1'
curl http://127.0.0.1:8080
hostname is e3655104f679 and hits b'2'
curl http://127.0.0.1:8080
hostname is 00ac6b67ed40 and hits b'3'
curl http://127.0.0.1:8080
hostname is 0d3c85986304 and hits b'4'
阅读 281

从转行到入门,记录我的自学成长之路

59 声望
15 粉丝
0 条评论
你知道吗?

从转行到入门,记录我的自学成长之路

59 声望
15 粉丝
宣传栏