配置docker的负载均衡
1.建立一个文件docker-compose.yml,具体内容如下:
This docker-compose.yml file tells Docker to do the following:(具体解释如下)
Run five instances of the image we uploaded in step 2 as a service called web, limiting each one to use, at most, 10% of the CPU (across all cores), and 50MB of RAM.
# 运行我们之前制作好放置到docker仓库的docker 镜像,限制每个使用的资源为10%的CPU和50MB的内存
Immediately restart containers if one fails. # 如果失败快速重启
Map port 80 on the host to web’s port 80. # 映射到外部的80端口
Instruct web’s containers to share port 80 via a load-balanced network called web net. (Internally, the containers themselves will publish to web’s port 80 at an ephemeral port.)
# 通过负载均衡分享80端口
Define the web net network with the default settings (which is a load-balanced overlay network).
#用默认的设置定义网络
2.Run your new load-balanced app
Before we can use the docker stack deploy command we’ll first run(用doker stack deploy命令之前必须先执行下边的命令)
[root@host1 ~]#docker swarm init
Note: We’ll get into the meaning of that command in part 4. If you don’t run docker swarm init you’ll get an error that “this node is not a swarm manager.”
Now let’s run it. You have to give your app a name – here it is set to getstartedlab:
# 运行命令,之前要先起一个名字,这里设置的是getstartedlab
[root@host1 ~]#docker stack deploy -c docker-compose.yml getstartedlab
See a list of the five containers you just launched:
[root@host1 ~]#docker stack ps getstartedlab
You can run curl http://localhost several times in a row, or go to that URL in your browser and hit refresh a few times. Either way, you’ll see the container ID randomly change, demonstrating the load-balancing; with each request, one of the five replicas is chosen at random to respond.
# 通过网址访问刷新,会看到页面的容器ID 不断的发生变化,演示着负载均衡的效果,随机的五选一来回复
3.Scale the app(规模化应用 )
You can scale the app by changing the replicas value in docker-compose.yml, saving the change, and re-running the docker stack deploy command:(当docker-compose.yml文件的内容发生变化时,可以通过重新执行docker stack deploy -c docker-compose.yml getstartedlab来重新部署,不需要先关闭再重新启动)
[root@host1 ~]#docker stack deploy -c docker-compose.yml getstartedlab
Docker will do an in-place update, no need to tear the stack down first or kill any containers.
4.Take down the app
Take the app down with docker stack rm:(关闭app)
[root@host1 ~]#docker stack rm getstartedlab
It’s as easy as that to stand up and scale your app with Docker. You’ve taken a huge step towards learning how to run containers in production. Up next, you will learn how to run this app on a cluster of machines.(下一节讲述如何在集群运行应用)