文中内容摘自Docker官网
提醒:请务必使用root帐号,以免在后面应用系统部署时,发生权限问题。
服务介绍
在分布式应用程序中, 应用程序的不同部分称为 "服务"。例如, 如果您设想视频共享站点, 它可能包括用于在数据库中存储应用程序数据的服务、用户上传内容后在后台进行视频转码的服务、前端服务等。
一个服务只运行一个映像, 但它编纂了映像的运行方式-它应该使用哪些端口, 容器的副本应该运行多少个, 以便确定该服务所需的资源, 等等。
通过一个名为 docker-compose.yml 文件可以设定服务运行的环境。
version: "3"
services:
web:
# replace username/repo:tag with your name and image details
image: username/repo:tag
deploy:
replicas: 5
resources:
limits:
cpus: "0.1"
memory: 50M
restart_policy:
condition: on-failure
ports:
- "4000:80"
networks:
- webnet
networks:
webnet:
This docker-compose.yml file tells Docker to do the following:
- Pull the image we uploaded in step 2 from the registry.
- Run 5 instances of that image as a service called web, limiting each one to use, at most, 10% of the CPU (across all cores), and 50MB of RAM.
- Immediately restart containers if one fails.
- Map port 4000 on the host to web’s port 80.
- Instruct web’s containers to share port 80 via a load-balanced network called webnet. (Internally, the containers themselves publish to web’s port 80 at an ephemeral port.)
- Define the webnet network with the default settings (which is a load-balanced overlay network).
基于负载平衡下运行应用
1. 启动负载均衡
docker swarm init
2. 运行应用
假定当前一个应用仅使用一个服务,一个服务下有5个映像副本,应用名称定义为getstartedlab:
docker stack deploy -c docker-compose.yml getstartedlab
3. 执行完上述脚本后,可以通过docker stack ls, docker service ls, docker container ls三个命令查看stack、service及container三层的具体情况。
4. docker的负载均衡是通过轮询的机制实现的,连续使用curl http://127.0.0.1:4000,可以发现docker返回了不同的container id
5. 如果调整了应用运行的副本数等参数,可以重新运行 docker stack deploy 命令,令应用重新执行。
下线应用
1. 下线应用
docker stack rm getstartedlab
2. 撤销负载均衡
docker swarm leave --force