【容器应用系列教程】Docker-compose容器编排工具

一、关于Docker-compose

二、Docker-compose工具安装

1.下载Docker-compose

截止教程撰写日期,最新版为v2.8.0

[root@harbor ~]# wget -O /usr/local/bin/docker-compose https://github.com/docker/compose/releases/download/v2.18.0/docker-compose-linux-x86_64

2.给予执行权限

[root@harbor ~]# chmod a+x /usr/local/bin/docker-compose

3.查看版本信息

[root@harbor ~]# docker-compose -v
Docker Compose version v2.18.0

三、Docker-compose工具使用教程

1.Docker-compose使用流程

A.规划目录

[root@harbor ~]# mkdir -p /opt/test/

B.编写docker-compose.yml文件

[root@harbor ~]# cd /opt/test/
[root@harbor test]# vim docker-compose.yml
version: '3'
services:
    web:
        image: nginx:latest
    redis:
        image: redis:latest

C.创建容器

[root@harbor test]# docker-compose up -d

[+] Building 0.0s (0/0)                                                  
[+] Running 3/3
 ✔ Network test_default    Created                                  0.0s 
 ✔ Container test-redis-1  Started                                  0.6s 
 ✔ Container test-web-1    Started                                  0.6s
  • 容器的命名规则:
    • 当前目录容器名称数字
[root@harbor test]# docker-compose ps -a

NAME                IMAGE               COMMAND                  SERVICE             CREATED             STATUS              PORTS
test-redis-1        redis:latest        "docker-entrypoint.s…"   redis               15 minutes ago      Up 15 minutes       6379/tcp
test-web-1          nginx:latest        "/docker-entrypoint.…"   web                 15 minutes ago      Up 15 minutes       80/tcp

2.Docker-compose常用操作

创建容器

需要提前准备好docker-compose.yml文件

# docker-compose up -d
  • --scale web=2横向扩展,将名称为web的容器启动两个
  • -f默认名称为docker-compose.yml文件,-f可指定其他文件名,不建议使用

查看容器

[root@harbor test]# docker-compose ps	#查看正在运行的容器

NAME                IMAGE               COMMAND                  SERVICE             CREATED             STATUS              PORTS
test-redis-1        redis:latest        "docker-entrypoint.s…"   redis               22 minutes ago      Up 22 minutes       6379/tcp
test-web-1          nginx:latest        "/docker-entrypoint.…"   web                 22 minutes ago      Up 22 minutes       80/tcp
[root@harbor test]# docker-compose ps -a	#查看所有容器(包括停止的)

NAME                IMAGE               COMMAND                  SERVICE             CREATED             STATUS              PORTS
test-redis-1        redis:latest        "docker-entrypoint.s…"   redis               15 minutes ago      Up 15 minutes       6379/tcp
test-web-1          nginx:latest        "/docker-entrypoint.…"   web                 15 minutes ago      Up 15 minutes       80/tcp

容器行为管理的操作

# docker-compose {start|stop|restart}

停止并删除容器

# docker-compose down

查看容器进程信息

[root@harbor test]# docker-compose top

test-redis-1
UID       PID     PPID    C    STIME   TTY   TIME       CMD
polkitd   11451   11415   0    11:05   ?     00:00:01   redis-server *:6379   

test-web-1
UID    PID     PPID    C    STIME   TTY   TIME       CMD
root   11431   11398   0    11:05   ?     00:00:00   nginx: master process nginx -g daemon off;   
101    11524   11431   0    11:05   ?     00:00:00   nginx: worker process                        
101    11525   11431   0    11:05   ?     00:00:00   nginx: worker process                        
101    11526   11431   0    11:05   ?     00:00:00   nginx: worker process                        
101    11527   11431   0    11:05   ?     00:00:00   nginx: worker process

docker-compose build

当目录下的dockerfile发生变动时,默认情况下,docker-compose并不会重构镜像,需要执行该命令手动重新构建,再执行docker-compose up -d重建容器

[root@localhost testCompose]# tree ./
./
├── docker-compose.yml
├── Dockerfile
├── file01.txt
└── file02.txt
[root@localhost testCompose]# cat docker-compose.yml 
version: '3'
services:
   web_server:
       build: ./
[root@localhost testCompose]# cat Dockerfile 
FROM nginx:latest

ADD file01.txt /tmp
ADD file02.txt /tmp

四、Docker-compose.yml文件

1.整体结构

version: "3"
services:
    容器名称:
        .........
        .........
    容器名称:
        .............
        .............
networks:
volumes:

2.容器命令下面的命令

指定创建容器的时候,使用的镜像

image: 镜像名称
version: '3'
services:
    webserver:
        image: nginx

数据持久化存储

volumes:
    - 物理目录:容器目录
version: '3'
services:
    dbserver:
        image: mysql:5.7
        volumes:
            - /mysql:/var/lib/mysql

创建容器的时候,执行的操作

command: "shell命令"
version: '3'
services:
    server:
        image: centos:7
        command: "sleep 120"
[root@harbor test]# docker ps
CONTAINER ID   IMAGE      COMMAND       CREATED         STATUS         PORTS     NAMES
328381ee82db   centos:7   "sleep 120"   3 seconds ago   Up 2 seconds             test-server-1

指定容器的网络连接

links:
    - 容器名称:别名
version: '3'
services:
    webserver:
        image: centos:7
        command: "sleep 120"
    server:
        image: centos:7
        tty: true	#用于模拟一个可持续运行的终端
        links:
            - webserver:web
[root@harbor test]# docker-compose up -d
[+] Building 0.0s (0/0)                                                  
[+] Running 3/3
 ✔ Network test_default        Created                              0.0s 
 ✔ Container test-webserver-1  Star...                              0.2s 
 ✔ Container test-server-1     Started                              0.4s 

[root@harbor test]# docker ps
CONTAINER ID   IMAGE      COMMAND       CREATED         STATUS         PORTS     NAMES
ff57f35756ff   centos:7   "/bin/bash"   8 seconds ago   Up 8 seconds             test-server-1
81f759b5b95e   centos:7   "sleep 120"   8 seconds ago   Up 8 seconds             test-webserver-1

[root@harbor test]# docker exec -it ff57 bash

[root@ff57f35756ff /]# ping web
PING web (172.20.0.2) 56(84) bytes of data.
64 bytes from test-webserver-1.test_default (172.20.0.2): icmp_seq=1 ttl=64 time=0.107 ms
64 bytes from test-webserver-1.test_default (172.20.0.2): icmp_seq=2 ttl=64 time=0.047 ms

发布服务(端口映射)和指定容器端口

ports:
    - 物理机端口:容器端口
expose:
    - 端口
version: '3'
services:
    webserver:
        image: nginx
        expose:
            - 80/tcp
        ports:
            - 80:80

传递环境变量

environment:
    key: value
    key: value
version: '3'
services:
    dbserver:
        image: mysql:5.7
        expose:
            - 3306/tcp
        ports:
            - 3306:3306
        environment:
            MYSQL_ROOT_PASSWORD: WWW.1.com
[root@harbor test]# docker ps
CONTAINER ID   IMAGE       COMMAND                   CREATED          STATUS          PORTS                                                  NAMES
591e6c5bd257   mysql:5.7   "docker-entrypoint.s…"   29 seconds ago   Up 28 seconds   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   test-dbserver-1

[root@harbor test]# docker exec -it 591e bash

bash-4.2# mysql -uroot -pWWW.1.com
mysql>

定义容器的依赖关系

指定容器的创建顺序

depends_on:
    - 容器名称
    - 容器名称

定义容器部署参数

deploy: 
    replicas: 3	#指定容器的副本数
    resources:		#限制容器资源
        limits:	#硬限制
            cpus: "2"
            memory: 2G
        reservations:	#软限制
            cpus: "1"
            memory: 1G

容器健康状态监测

healthcheck:
	test: ["CMD", "curl", "-f", "http://localhost"]
	interval: 10s	#监测10s
	timeout: 10s	#超时10s未相应,就判定容器挂掉
	retries: 3	#重试3次
	start_period: 40s	#容器启动40s后开始监测

容器网络模式

network_mode: "bridge"
network_mode: "host"
network_mode: "none"

3.实验

A.使用docker-compose部署Wordpress论坛,并且数据库需要配置主从复制环境

创建数据库用到的数据目录
[root@harbor wordpress]# mkdir -p /mysql/{master_data,slave,data}
配置主库配置文件
[root@harbor wordpress]# vim /mysql/master_my.cnf
[mysqld]
server_id=10
log_bin=master
gtid_mode=on
enforce_gtid_consistency=true
collation-server = utf8_general_ci
character-set-server = utf8	#设置默认建库使用utf8字符集
配置从库配置文件
[root@harbor wordpress]# vim /mysql/slave_my.cnf
[mysqld]
server_id=11
log_bin=slave
gtid_mode=on
enforce_gtid_consistency=true
collation-server = utf8_general_ci
character-set-server = utf8
编写docker-compose
[root@harbor wordpress]# mkdir /wordpress
[root@harbor wordpress]# cd /wordpress
[root@harbor wordpress]# vim docker-compose.yml
version: '3'
services: 
    master_db:
        image: mysql:5.7
        volumes: 
            - /mysql/master_data:/var/lib/mysql
            - /mysql/master_my.cnf:/etc/my.cnf
        environment: 
            MYSQL_ROOT_PASSWORD: WWW.1.com
            MYSQL_DATABASE: wordpress
            MYSQL_USER: wordpress
            MYSQL_PASSWORD: WWW.1.com
    slave_db:
        image: mysql:5.7
        volumes: 
            - /mysql/slave_data:/var/lib/mysql
            - /mysql/slave_my.cnf:/etc/my.cnf
        environment: 
            MYSQL_ROOT_PASSWORD: WWW.1.com
        links:
            - master_db:masterdb
    redis:
        image: redis
        ports:
            - 6379:6379
    wp:
        image: wordpress
        links:
            - master_db:masterdb
        environment:
            WORDPRESS_DB_HOST: masterdb
            WORDPRESS_DB_USER: wordpress
            WORDPRESS_DB_PASSWORD: WWW.1.com
            WORDPRESS_DB_NAME: wordpress
            WORDPRESS_TABLE_PREFIX: wp_
        ports:
            - 80:80
        depends_on:
            - master_db
            - slave_db
            - redis
创建容器
[root@harbor wordpress]# docker-compose up -d
[+] Building 0.0s (0/0)                                                  
[+] Running 5/5
 ✔ Network wordpress_default        Created                         0.0s 
 ✔ Container wordpress-redis-1      Started                         0.4s 
 ✔ Container wordpress-master_db-1  Started                         0.4s 
 ✔ Container wordpress-slave_db-1   Started                         0.6s 
 ✔ Container wordpress-wp-1         S...                            0.8s
配置主从复制环境
[root@harbor wordpress]# docker exec -it wordpress-master_db-1 /bin/bash
bash-4.2# mysql -uroot -pWWW.1.com
mysql> grant replication slave on *.* to 'repluser'@'%' identified by 'WWW.1.com';
mysql> exit
Bye
bash-4.2# exit
exit
[root@harbor wordpress]# docker exec -it wordpress-slave_db-1 /bin/bash
bash-4.2# mysql -uroot -pWWW.1.com
mysql> change master to
    -> master_host="masterdb",
    -> master_user="repluser",
    -> master_password="WWW.1.com",
    -> master_auto_position=1;
Query OK, 0 rows affected, 2 warnings (0.01 sec)
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: masterdb
                  Master_User: repluser
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master.000003
          Read_Master_Log_Pos: 481
               Relay_Log_File: 9e6207d2c18b-relay-bin.000003
                Relay_Log_Pos: 688
        Relay_Master_Log_File: master.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
安装Wordpress

过程省略

配置redis

docker-compose01

修改redis配置文件
[root@harbor wordpress]# docker cp wordpress-wp-1:/var/www/html/wp-content/plugins/redis-cache/includes/object-cache.php /root/
[root@harbor wordpress]# vim /root/object-cache.php
protected function build_parameters() {
        $parameters = [
            'scheme' => 'tcp',
            'host' => '192.168.140.16',
            'port' => 6379,
            'database' => 0,
            'timeout' => 1,
            'read_timeout' => 1,
            'retry_interval' => null,
            'persistent' => false,
        ];

[root@harbor wordpress]# docker cp /root/object-cache.php wordpress-wp-1:/var/www/html/wp-content/plugins/redis-cache/includes/
[root@harbor wordpress]# docker cp wordpress-wp-1:/var/www/html/wp-config.php /root/
[root@harbor wordpress]# vim /root/wp-config.php
#在文件末尾添加以下内容
define('WP_REDIS_HOST', '192.168.140.16');      #物理机IP
define('WP_REDIS_PORT', '6379');
define('WP_REDIS_DATABASE', '0');

[root@harbor wordpress]# docker cp /root/wp-config.php wordpress-wp-1:/var/www/html/
启动redis插件

container07