traefik是一個使你把微服務暴露出來變的更容易的http反向代理和負載均衡軟件。traefik支持K8S、docker swarm、mesos、consul、etcd、zookeeper等基礎設施組件,個人認爲更適合容器化的微服務,traefik的配置會自動的、動態的配置更新自己。traefik的原理在另一篇講解,本章直接實戰看效果。
場景
本篇主要模擬的是traefik+docker swarm mode的場景,由traefik自動發現swarm mode下的service
環境
ubuntu16.04-1 | swarm manager | traefik |
ubuntu16.04-2 | swarm works | |
ubuntu16.04-3 | swarm works |
ps:還是之前文章做實驗的swarm集羣
下載traefik
wget 'https://github-production-release-asset-2e65be.s3.amazonaws.com/42408804/b7288f00-a48e-11e8-817e-298aa1a8bae9?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20180903%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180903T065922Z&X-Amz-Expires=300&X-Amz-Signature=4d4a6a61122a5e0ac8aaae5da30883d555db307c2a9dbe1e300fb1dc2decb0a2&X-Amz-SignedHeaders=host&actor_id=12913767&response-content-disposition=attachment%3B%20filename%3Dtraefik_linux-amd64&response-content-type=application%2Foctet-stream'
ps:把下載完的traefik_linux-amd64二進制文件重命名成traefik,上傳到鏡像製作服務器。
鏡像製作
Dockfile
FROM scratch
COPY ./traefik /
EXPOSE 80
ENTRYPOINT ["/traefik"]
編譯image
docker build -t traefik .
上傳image
docker tag traefik 172.31.68.241/library/traefik
docker push 172.31.68.241/library/traefik
部署traefik
創建網絡
docker network create --driver=overlay traefik-net
ps:traefik和app要在同一個網絡內,否則traefik識別不到app
部署traefik
docker service create \
--name traefik \
--constraint=node.role==manager \
--publish 8090:80 --publish 8080:8080 \
--mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \
--network traefik-net \
172.31.68.241/library/traefik \
--docker \
--docker.swarmMode \
--docker.domain=example.org \
--docker.watch \
--logLevel=DEBUG \
--web
查看web
http://172.31.68.241:8080/dashboard/
輪訓訪問app
docker service create --replicas 2 --network traefik-net --label traefik.port=80 --label traefik.frontend.rule=Host:test.example.org --name hello 172.31.68.241/library/friendlyhello
驗證
curl -H Host:test.example.org http://172.31.68.241:8090
會話粘滯訪問app
docker service create --replicas 2 --network traefik-net --label traefik.port=80 --label traefik.frontend.rule=Host:test.example.org --label traefik.backend.loadbalancer.sticky=true --name hello 172.31.68.241/library/friendlyhello
驗證
curl -c cookies.txt -H Host:test.example.org http://172.31.68.241:8090
curl -b cookies.txt -H Host:test.example.org http://172.31.68.241:8090