文中內容摘自Docker官網
服務介紹
在分佈式應用程序中, 應用程序的不同部分稱爲 "服務"。例如, 如果您設想視頻共享站點, 它可能包括用於在數據庫中存儲應用程序數據的服務、用戶上傳內容後在後臺進行視頻轉碼的服務、前端服務等。
一個服務只運行一個映像, 但它編纂了映像的運行方式-它應該使用哪些端口, 容器的副本應該運行多少個, 以便確定該服務所需的資源, 等等。
通過一個名爲 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