docker三剑客之compose
一.Docker Compose简介
- 微服务架构的应用系统一般包含若干个微服务,每个微服务一般都会部署多个实例,如果每个微服务都要手动启停,那么效率之低,维护量之大可想而知。
- Docker Compose是一种编排服务,基于pyhton语言实现,是一个用于在 Docker 上定义并运行复杂应用的工具,可以让用户在集群中部署分布式应用。
- 用户可以很容易地用一个配置文件定义一个多容器的应用,然后使用一条指令安装这个应用的所有依赖,完成构建。
- 解决了容器与容器之间如何管理编排的问题。
Docker Compose 中有两个重要的概念:
- 服务 (service) :一个应用的容器,实际上可以包括若干运行相同镜像的容器实例。
- 项目 (project) :由一组关联的应用容器组成的一个完整业务单元,在 docker-compose.yml 文件中定义。
Docker Compose 常用命令
- Build: 构建或重新构建服务。
- kill:强制停止服务容器。
- logs:查看服务的输出。
- port:打印绑定的公共端口。
- ps:列出所有容器。
- pull:拉取服务所需镜像。
- rm:删除停止的服务容器。
- up:构建并启动容器。
二.Docker Compose部署haproxy
部署结构
创建compose目录
mkdir compose
docker-compose 二进制文件放入/usr/local/bin
haproxy镜像导入
docker load -i haproxy.tar
创建默认发布页index.html
[root@server1 compose]# echo web1 > web1/index.html
[root@server1 compose]# echo web2 > web2/index.html
haproxy配置文件haproxy.cfg
[root@server1 compose]# cat haproxy/haproxy.cfg
#
# This is a sample configuration. It illustrates how to separate static objects
# traffic from dynamic traffic, and how to dynamically regulate the server load.
#
# It listens on 192.168.1.10:80, and directs all requests for Host 'img' or
# URIs starting with /img or /css to a dedicated group of servers. URIs
# starting with /admin/stats deliver the stats page.
#
global
maxconn 65535
stats socket /var/run/haproxy.stat mode 600 level admin
log 127.0.0.1 local0
uid 200
gid 200
daemon
defaults
mode http
log global
option httplog
option dontlognull
monitor-uri /monitoruri
maxconn 8000
timeout client 30s
retries 2
option redispatch
timeout connect 5s
timeout server 5s
stats uri /admin/stats
# The public 'www' address in the DMZ
frontend public
bind *:80 name clear
#bind 192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem
#use_backend static if { hdr_beg(host) -i img }
#use_backend static if { path_beg /img /css }
default_backend dynamic
# The static backend backend for 'Host: img', /img and /css.
backend dynamic
balance roundrobin
server a web1:80 check inter 1000
server b web2:80 check inter 1000
compose脚本docker-compose.yml
[root@server1 compose]# cat docker-compose.yml
version: "3.8"
services:
web1:
image: nginx
networks:
- webnet
volumes:
- ./web1:/usr/share/nginx/html
web2:
image: nginx
networks:
- webnet
volumes:
- ./web2:/usr/share/nginx/html
haproxy:
image: haproxy
networks:
- webnet
volumes:
- ./haproxy:/usr/local/etc/haproxy
ports:
- "80:80"
networks:
webnet:
执行
[root@server1 compose]# docker-compose up -d
\Creating network "compose_webnet" with the default driver
Creating compose_web1_1 ... done
Creating compose_web2_1 ... done
Creating compose_haproxy_1 ... done
查看容器
测试,负载均衡成功
[root@server1 web1]# cat index.html
web1
[root@server1 web1]# curl 172.25.3.1
web2
[root@server1 web1]# curl 172.25.3.1
web1
[root@server1 web1]# curl 172.25.3.1
web2