本文将参考官方文档,详细讲解 Docker 服务的相关内容。
为了扩展应用程序并启用负载平衡,必须在分布式应用程序的层次结构中提升一级:服务。
创建一个docker-compose.yml文件
在 Docker 平台中,只需要创建一个docker-compose.yml文件,就可以实现服务的定义,运行与扩展。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21# 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:
docker-compose.yml文件告诉 Docker 执行以下操作:
- 将指定的镜像从注册中心 pull 下来
- 将该镜像的5个实例作为名为
web的服务运行,限制每个实例最多使用10%的CPU和50MB的内存资源 - 如果一个实例失败了,则立即重启容器
- 将主机的
4000端口映射到web服务的80端口 - 指定
web服务的容器通过称为webnet的负载均衡网络共享80端口。 - 使用默认设置定义
webnet网络(这是一个负载均衡网络)
运行新的负载均衡 app
先运行命令
docker swarm init不使用该命令会报错:
1
Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.
将app命名为
getstartedlab,并运行1
2
3
4$ docker stack deploy -c docker-compose.yml getstartedlab
# 查看服务信息
$ docker service ls服务里运行的单个容器称为一个
task,查看service中的task信息:1
2
3
4
5
6
7
8$ docker service ps getstartedlab_web
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
nnw0bqh9kdh7 getstartedlab_web.1 cj1406942109/get-started:first-demo linuxkit-00155d0ae915 Running Running 2 minutes ago
hdeo9vn0hzo4 getstartedlab_web.2 cj1406942109/get-started:first-demo linuxkit-00155d0ae915 Running Running 2 minutes ago
f7l22z600893 getstartedlab_web.3 cj1406942109/get-started:first-demo linuxkit-00155d0ae915 Running Running 2 minutes ago
h7yqtkopoqrf getstartedlab_web.4 cj1406942109/get-started:first-demo linuxkit-00155d0ae915 Running Running 2 minutes ago
vyxbnymk9up7 getstartedlab_web.5 cj1406942109/get-started:first-demo linuxkit-00155d0ae915 Running Running 2 minutes ago列出容器的时候可以看到
taks的信息1
$ docker container ls -q
可以多次运行命令
curl -4 http://localhost:4000或者在浏览器里输入 URL 并多次刷新查看效果,可以看到容器的 ID 发生改变,表明启用了负载均衡可以通过修改
docker-compose.yml文件中的replicas值来扩展 app,保存文件,重新运行docker stack deploy -c docker-compose.yml getstartedlab命令即可拆卸
app和swarm1
2
3
4
5# Take the app down with docker stack rm
$ docker stack rm getstartedlab
# Take down the swarm
$ docker swarm leave --force