Docker单机编排容器

当在宿主机启动较多的容器时候,如果都是手动操作会觉得比较麻烦而且容易出错, 并且每个容器之间也会有先后启动的顺序依赖等。这个时候推荐使用 docker 单机 编排工具 docker-composedocker-compose 是 docker 容器的一种单机编排服务, docker-compose 是一个管理多个容器的工具,比如可以解决容器之间的依赖关系, 就像启动一个 nginx 前端服务的时候会调用后端的 tomcat,那就得先启动 tomcat, 但是启动 tomcat 容器还需要依赖数据库,那就还得先启动数据库,docker-compose 就可以解决这样的嵌套依赖关系,其完全可以替代 docker run 对容器进行创建、启动 和停止。

docker-compose 项目是 Docker 官方的开源项目,负责实现对 Docker 容器集群的快 速编排,docker-compose 将所管理的容器分为三层,分别是工程(project),服务 (service)及容器(container)。

docker-compose 是一个用于定义和运行多个容器 Docker 应用程序的工具。使用 Compose,可以使用 YAML 文件来配置应用程序的服务。然后,使用一个命令,从 配置中创建并启动所有服务。所以在使用 docker-compose 时编写比较规范的.yaml 或则.yml 文件是比较重要的。Compose 文件就是一个 YAML 文件,用其来定义 服务、网络和数据卷等。docker-compose 默认会在当前目录找该文件,即 ./docker-compose.yml

Docker-compose 项目地址

docker-compose.yaml 文件示例:

 1version: "3.7"
 2services:
 3  redis:
 4    image: redis:alpine
 5    ports:
 6      - "6379"
 7    networks:
 8      - frontend
 9    deploy:
10      replicas: 2
11      update_config:
12        parallelism: 2
13        delay: 10s
14      restart_policy:
15        condition: on-failure
16
17  db:
18    image: postgres:9.4
19    volumes:
20      - db-data:/var/lib/postgresql/data
21    networks:
22      - backend
23    deploy:
24      placement:
25        constraints: [node.role == manager]
26
27  vote:
28    image: dockersamples/examplevotingapp_vote:before
29    ports:
30      - "5000:80"
31    networks:
32      - frontend
33    depends_on:
34      - redis
35    deploy:
36      replicas: 2
37      update_config:
38        parallelism: 2
39      restart_policy:
40        condition: on-failure
41
42  result:
43    image: dockersamples/examplevotingapp_result:before
44    ports:
45      - "5001:80"
46    networks:
47      - backend
48    depends_on:
49      - db
50    deploy:
51      replicas: 1
52      update_config:
53        parallelism: 2
54        delay: 10s
55      restart_policy:
56        condition: on-failure
57
58  worker:
59    image: dockersamples/examplevotingapp_worker
60    networks:
61      - frontend
62      - backend
63    deploy:
64      mode: replicated
65      replicas: 1
66      labels: [APP=VOTING]
67      restart_policy:
68        condition: on-failure
69        delay: 10s
70        max_attempts: 3
71        window: 120s
72      placement:
73        constraints: [node.role == manager]
74
75  visualizer:
76    image: dockersamples/visualizer:stable
77    ports:
78      - "8080:8080"
79    stop_grace_period: 1m30s
80    volumes:
81      - "/var/run/docker.sock:/var/run/docker.sock"
82    deploy:
83      placement:
84        constraints: [node.role == manager]
85
86networks:
87  frontend:
88  backend:
89
90volumes:
91  db-data:

一. 安装 docker-compose

1.1 安装 python-pip 包管理器

在 linux 平台,安装python-pip 包会安装 pip 命令,pip 命令是一个 pyhton 安装包的安装管理工具,其类似于 ubuntu 的 apt 或者 redhat 的 yum,但是 pip 只安装 python 相关的安装包。pip 工具可以在多种 操作系统安装和使用。

Ubuntu1804 安装

1root@ubuntu-suosuoli-node1:~# apt update
2root@ubuntu-suosuoli-node1:~# apt install python3-pip

CentOS 安装

1~$ yum install epel-release
2~$ yum install -y python3-pip

1.2 安装 docker-compose

Ubuntu 1804

 1root@ubuntu-suosuoli-node1:~# pip3 install docker-compose
 2root@ubuntu-suosuoli-node1:~# docker-compose version
 3docker-compose version 1.25.4, build unknown
 4docker-py version: 4.2.0
 5CPython version: 3.6.9
 6OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
 7
 8root@ubuntu-suosuoli-node1:~# docker-compose --help
 9Define and run multi-container applications with Docker.
10
11Usage:
12  docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
13  docker-compose -h|--help
14
15## 常用选项:
16-f,–file FILE         #指定Compose模板文件,默认为docker-compose.yml。
17-p,–project-name NAME #指定项目名称,默认将使用当前所在目录名称作为项目名。
18--verbose              #显示更多输出信息
19--log-level LEVEL      #定义日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)
20--no-ansi              #不显示ANSI控制字符
21-v, --version          #显示版本
22config  -q #查看当前配置,没有错误不输出任何信息
23build     # 通过docker-compose构建镜像
24bundle    # 从当前docker compose文件生成一个以当前目录为名称的从Compose 文件生成一个分布式应用程序捆绑包(DAB)。
25create    # 创建服务
26down      # 停止和删除所有容器、网络、镜像和卷
27
28events    # 从容器接收实时事件,可以指定json日志格式,如
29    # docker-compose  events --json
30
31exec      # 进入指定容器进行操作
32help      # 显示帮助细信息
33images    # 显示当前服务器的docker镜像信息,和docker images基本一致
34kill      # 强制终止运行中的容器
35logs      # 查看容器的日志
36pause     # 暂停服务
37
38port      # 查看端口
39    # docker-compose port  --protocol=tcp nginx 80
40
41ps        # 列出容器
42pull      # 重新拉取镜像
43push      # 上传镜像
44restart   # 重启服务
45rm        # 删除已经停止的服务
46run       # 一次性运行容器,等于docker run --rm
47
48scale     # 设置指定服务运行的容器个数
49    # docker-compose  scale nginx=2
50
51start     # 启动服务
52stop      # 停止服务
53top       # 显示容器运行状态
54unpause   # 取消暂定
55up        # 创建并启动容器
56version   # 显示docker-compose版本信息

CentOS

1~$ pip3 install docker-compose
2~$ docker-compose version
3~$ docker-compose --help

注:官方二进制下载地址:https://github.com/docker/compose/releases

二. 使用 docker-compose 启动单个容器

编写 yaml 格式的 compose 文件时,可以在任意目录新建.yaml文件,并从 该目录启动容器。

2.1 编写构建单个容器的 compose 文件

编写 yml 格式的 docker-compose 文件,启动一个 nginx 服务,yaml 文档 的语法严格要求上下各行缩进的关系。

1root@ubuntu-suosuoli-node1:~# mkdir  /data/compose
2root@ubuntu-suosuoli-node1:~# cd /data/compose
3root@ubuntu-suosuoli-node1:/data/compose# vim docker-compose.yaml
1service-nginx:
2  image: nginx:compiled_V1
3  expose:
4    - 80
5    - 443
6  ports:
7    - "80:80"
8    - "443:443"

2.2 启动容器

在 docker compose 文件所在的目录执行docker-compose up -d 不加-d选项表示前台启动容器。

1root@ubuntu-suosuoli-node1:/data/compose# docker-compose up -d
2Creating compose_service-nginx_1 ... done

2.3 访问 web 测试

1root@ubuntu-suosuoli-node1:/data/compose# ip addr show eth0 | grep inet
2    inet 192.168.100.13/24 brd 192.168.100.255 scope global dynamic eth0

2.4 compose 启动的容器名

容器的在启动的时候,会给容器自定义一个名称,在 service name 后面加_1 在前面加当前目录名compose_

1root@ubuntu-suosuoli-node1:/data/compose# docker ps
2CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                         NAMES
39060a76a2dc4        nginx:compiled_V1   "nginx -g 'daemon of…"   2 minutes ago       Up 2 minutes        0.0.0.0:80->80/tcp, 443/tcp   compose_service-nginx_1

2.5 自定义容器名使用comtainer_name

1root@ubuntu-suosuoli-node1:/data/compose# vim docker-compose.yaml
1service-nginx:
2  image: nginx:compiled_V1
3  container_name: service-nginx
4  expose:
5    - 80
6    - 443
7  ports:
8    - "80:80"
9    - "443:443"
1root@ubuntu-suosuoli-node1:/data/compose# docker-compose down
2Stopping compose_service-nginx_1 ... done
3Removing compose_service-nginx_1 ... done
4root@ubuntu-suosuoli-node1:/data/compose# docker-compose up -d
5Creating service-nginx ... done
6root@ubuntu-suosuoli-node1:/data/compose# docker ps
7CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES
8f8e402b17985        nginx:compiled_V1   "nginx -g 'daemon of…"   3 seconds ago       Up 2 seconds        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   service-nginx

2.6 查看容器进程

1root@ubuntu-suosuoli-node1:/data/compose# docker-compose ps
2    Name              Command          State                    Ports
3---------------------------------------------------------------------------------------
4service-nginx   nginx -g daemon off;   Up      0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp

三. 使用 docker-compose 启动多个容器

3.1 编写构建多个容器的 compose 文件

1root@ubuntu-suosuoli-node1:/data/compose# vim docker-compose.yaml
 1service-nginx:
 2  image: nginx:compiled_V1
 3  container_name: service-nginx
 4  expose:
 5    - 80
 6    - 443
 7  ports:
 8    - "80:80"
 9    - "443:443"
10
11service-tomcat-app1:
12  images: tomcat-business:app1
13  container_name: tomcat-app1
14  expose:
15    - 8080
16  ports:
17    - "8080:8080"

3.2 重启容器

 1root@ubuntu-suosuoli-node1:/data/compose# docker-compose stop
 2Stopping service-nginx ... done
 3root@ubuntu-suosuoli-node1:/data/compose# docker-compose down
 4Removing service-nginx ... done
 5
 6root@ubuntu-suosuoli-node1:/data/compose# docker-compose up -d
 7Creating tomcat-app1   ... done
 8Creating service-nginx ... done
 9
10root@ubuntu-suosuoli-node1:/data/compose# ss -tnl | grep 80
11LISTEN   0         20480                     *:8080                   *:*
12LISTEN   0         20480                     *:80                     *:*
13...
14root@ubuntu-suosuoli-node1:/data/compose# lsof -i:80
15COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
16docker-pr 15625 root    4u  IPv6 715730      0t0  TCP *:http (LISTEN)
17root@ubuntu-suosuoli-node1:/data/compose# lsof -i:8080
18COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
19docker-pr 15637 root    4u  IPv6 715754      0t0  TCP *:http-alt (LISTEN)

3.3 访问 web 测试

3.4 单机编排常用命令

3.4.1 重启单个容器

使用docker-compose restart service_name重启某个容器

 1root@ubuntu-suosuoli-node1:/data/compose# cat docker-compose.yaml
 2service-nginx:
 3  image: nginx:compiled_V1
 4  container_name: service-nginx
 5  expose:
 6    - 80
 7    - 443
 8  ports:
 9    - "80:80"
10    - "443:443"
11
12service-tomcat-app1:
13  image: tomcat-business:app1
14  container_name: tomcat-app1
15  expose:
16    - 8080
17  ports:
18    - "8080:8080"
19root@ubuntu-suosuoli-node1:/data/compose# docker-compose  restart service-nginx
20Restarting service-nginx ... done
21root@ubuntu-suosuoli-node1:/data/compose# docker-compose  restart service-tomcat-app1
22Restarting tomcat-app1 ... done

3.4.2 重启所有容器

使用docker-compose restart重启所有容器

1root@ubuntu-suosuoli-node1:/data/compose# docker-compose restart
2Restarting service-nginx ... done
3Restarting tomcat-app1   ... done

3.4.3 停止后启动单个容器

1root@ubuntu-suosuoli-node1:/data/compose# docker-compose stop service-nginx
2Stopping service-nginx ... done
3root@ubuntu-suosuoli-node1:/data/compose# docker-compose start service-nginx
4Starting service-nginx ... done

3.4.4 停止和启动所有容器

1root@ubuntu-suosuoli-node1:/data/compose# docker-compose stop
2Stopping service-nginx ... done
3Stopping tomcat-app1   ... done
4root@ubuntu-suosuoli-node1:/data/compose# docker-compose start
5Starting service-nginx       ... done
6Starting service-tomcat-app1 ... done

四. 定义数据卷

4.1 创建文件和目录

1root@ubuntu-suosuoli-node1:/data/compose# ll /data/app1
2total 12
3drwxr-xr-x  2 root root 4096 Feb 25 17:25 ./
4drwxr-xr-x 10 root root 4096 Feb 29 11:07 ../
5-rw-r--r--  1 root root   16 Feb 25 20:47 index.html
6root@ubuntu-suosuoli-node1:/data/compose# cat /data/app1/index.html
7This is app1...

4.2 编写 compose 文件

1root@ubuntu-suosuoli-node1:/data/compose# vim volume-compose.yaml
 1service-nginx:
 2  image: nginx:compiled_V1
 3  container_name: nginx-web1
 4  volumes:
 5    - /data/app1/:/usr/local/nginx/html/
 6  expose:
 7    - 80
 8    - 443
 9  ports:
10    - "80:80"
11    - "443:443"
12
13service-tomcat-app1:
14  image: tomcat-business:app1
15  container_name: tomcat-app1
16  expose:
17    - 8080
18  ports:
19    - "8080:8080"

4.3 重启容器

1root@ubuntu-suosuoli-node1:/data/compose# docker-compose down
2Stopping service-nginx ... done
3Stopping tomcat-app1   ... done
4Removing service-nginx ... done
5Removing tomcat-app1   ... done
6
7root@ubuntu-suosuoli-node1:/data/compose# docker-compose -f ./volume-compose.yaml up -d
8Creating tomcat-app1 ... done
9Creating nginx-web1  ... done

4.4 访问 web 验证

 1root@ubuntu-suosuoli-node1:/data/compose# docker ps
 2CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                                        NAMES
 32e7244785408        nginx:compiled_V1      "nginx -g 'daemon of…"   3 minutes ago       Up 3 minutes        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp     nginx-web1
 4d8c537c89088        tomcat-business:app1   "/apps/tomcat/bin/ru…"   3 minutes ago       Up 3 minutes        8005/tcp, 8009/tcp, 0.0.0.0:8080->8080/tcp   tomcat-app1
 5root@ubuntu-suosuoli-node1:/data/compose# docker exec -it nginx-web1 /bin/bash
 6[root@2e7244785408 /]# cat /usr/local/nginx/html/index.html
 7This is app1...
 8[root@2e7244785408 /]# exit
 9exit
10root@ubuntu-suosuoli-node1:/data/compose# cat /data/app1/index.html
11This is app1...
12

五. 单机版 nginx+tomcat 部署示例

编写 docker-compose.yml 文件,实现单机版本的 nginx+tomcat 的动静分离 web 站点,要求从 nginx 作为访问入口,当访问指定 URL 的时候转发至 tomcat 服务 器响应。

5.1 制作 HAProxy 镜像

5.1.1 HAProxy 镜像上下文

1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/system/centos/haproxy# ll
2total 24
3drwxr-xr-x 2 root root 4096 Feb 25 10:41 ./
4drwxr-xr-x 3 root root 4096 Feb 20 16:59 ../
5-rwxr--r-- 1 root root   48 Feb 20 17:15 docker_build_cmd.sh*
6-rw-r--r-- 1 root root  768 Feb 20 17:34 Dockerfile
7-rw-r--r-- 1 root root    0 Feb 25 10:41 haproxy-2.0.5.tar.gz
8-rw-r--r-- 1 root root  714 Feb 20 17:13 haproxy.cfg
9-rwxr-xr-x 1 root root   77 Feb 20 17:36 run_haproxy.sh*

5.1.2 Dockerfile

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/system/centos/haproxy# cat Dockerfile
 2# A HAProxy image based on centos-base:v1 with some tools installed
 3
 4FROM centos-base:v1
 5
 6RUN yum install -y yum install gcc gcc-c++ glibc glibc-devel \
 7    pcre pcre-devel openssl openssl-devel systemd-devel net-tools \
 8    vim iotop bc zip unzip zlib-devel lrzsz tree screen lsof tcpdump \
 9    wget ntpdate
10
11ADD haproxy-2.0.5.tar.gz /usr/local/src/
12
13RUN cd /usr/local/src/haproxy-2.0.5 && \
14    make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 \
15    USE_SYSTEMD=1 USE_CPU_AFFINITY=1 PREFIX=/usr/local/haproxy && \
16    make install PREFIX=/usr/local/haproxy && \
17    cp haproxy /usr/sbin/ && \
18    mkdir /usr/local/haproxy/run
19
20ADD haproxy.cfg /etc/haproxy/
21
22ADD run_haproxy.sh /usr/bin
23
24EXPOSE 80 9999
25
26CMD ["/usr/bin/run_haproxy.sh"]

5.1.3 HAProxy 配置文件

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/system/centos/haproxy# cat haproxy.cfg
 2global
 3chroot /usr/local/haproxy
 4#stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
 5uid 99
 6gid 99
 7daemon
 8nbproc 1
 9pidfile /usr/local/haproxy/run/haproxy.pid
10log 127.0.0.1 local3 info
11
12defaults
13option http-keep-alive
14option  forwardfor
15mode http
16timeout connect 300000ms
17timeout client  300000ms
18timeout server  300000ms
19
20listen stats
21 mode http
22 bind 0.0.0.0:9999
23 stats enable
24 log global
25 stats uri     /haproxy-status
26 stats auth    haadmin:stevenux
27
28listen  web_port_80
29 bind 0.0.0.0:80
30 mode http
31 log global
32 balance roundrobin
33 server web1  127.0.0.1:8800  check inter 3000 fall 2 rise 5
34
35listen  web_port_443
36 bind 0.0.0.0:443
37 mode http
38 log global
39 balance roundrobin
40 server web1  127.0.0.1:8443  check inter 3000 fall 2 rise 5

5.1.4 HAProxy 运行脚本

1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/system/centos/haproxy# cat run_haproxy.sh
2#!/bin/bash
3/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg
4tail -f /etc/hosts

5.1.5 镜像构建脚本

1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/system/centos/haproxy# cat docker_build_cmd.sh
2#!/bin/bash
3docker build -t haproxy-ubuntu:v1 .

5.1.6 构建 HAProxy 镜像

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/system/centos/haproxy# ./docker_build_cmd.sh
 2Sending build context to Docker daemon  2.546MB
 3Step 1/8 : FROM centos-base:v1
 4 ---> 729c515f2078
 5Step 2/8 : RUN yum install -y yum install gcc gcc-c++ glibc glibc-devel     pcre pcre-devel openssl openssl-devel systemd-devel net-tools     vim iotop bc zip unzip zlib-devel lrzsz tree screen lsof tcpdump     wget ntpdate
 6 ---> Using cache
 7 ---> e8cfccf03783
 8Step 3/8 : ADD haproxy-2.0.5.tar.gz /usr/local/src/
 9 ---> Using cache
10 ---> a6b31b35ffec
11Step 4/8 : RUN cd /usr/local/src/haproxy-2.0.5 &&     make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1     USE_SYSTEMD=1 USE_CPU_AFFINITY=1 PREFIX=/usr/local/haproxy &&     make install PREFIX=/usr/local/haproxy &&     cp haproxy /usr/sbin/ &&     mkdir /usr/local/haproxy/run
12 ---> Using cache
13 ---> 48628430e4a9
14Step 5/8 : ADD haproxy.cfg /etc/haproxy/
15 ---> c28219089d8e
16Step 6/8 : ADD run_haproxy.sh /usr/bin
17 ---> 4e61a58ce316
18Step 7/8 : EXPOSE 80 9999
19 ---> Running in cfe69dd4b8e6
20Removing intermediate container cfe69dd4b8e6
21 ---> aea10882c7be
22Step 8/8 : CMD ["/usr/bin/run_haproxy.sh"]
23 ---> Running in 5c9e9907ee16
24Removing intermediate container 5c9e9907ee16
25 ---> 12599307af4a
26Successfully built 12599307af4a
27Successfully tagged haproxy-ubuntu:v1

5.2 准备 nginx 镜像

5.2.1 镜像上下文

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/web/nginx/ubuntu-nginx# pwd
 2/opt/dockerfile/dockerfile-example/web/nginx/ubuntu-nginx
 3root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/web/nginx/ubuntu-nginx# ll
 4total 1044
 5drwxr-xr-x 2 root root    4096 Feb 20 16:35 ./
 6drwxr-xr-x 4 root root    4096 Feb 25 09:57 ../
 7-rwxr--r-- 1 root root      45 Feb 20 16:34 docker_build_cmd.sh*
 8-rw-r--r-- 1 root root     610 Feb 20 16:33 Dockerfile
 9-rw-r--r-- 1 root root 1032630 Feb 20 16:35 nginx-1.16.1.tar.gz
10-rw-r--r-- 1 root root    2674 Feb 20 16:34 nginx.conf
11-rw-r--r-- 1 root root   10240 Feb 20 16:35 suosuoli.tar.gz
12

5.2.2 构建镜像

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/web/nginx/ubuntu-nginx# ./docker_build_cmd.sh
 2Sending build context to Docker daemon  1.051MB
 3Step 1/8 : FROM ubuntu-base:v1
 4 ---> cea7344c8fbf
 5Step 2/8 : ADD nginx-1.16.1.tar.gz /usr/local/src
 6 ---> Using cache
 7 ---> b53d38ca4edc
 8Step 3/8 : RUN cd /usr/local/src/nginx-1.16.1 &&     ./configure --prefix=/apps/nginx &&     make && make install &&     ln -sv /apps/nginx/sbin/nginx /usr/bin &&     rm -rf /usr/local/src/nginx-1.16.1 &&     rm -rf /usr/local/src/nginx-1.16.1.tar.gz
 9 ---> Using cache
10 ---> dd6e13932516
11Step 4/8 : ADD nginx.conf /apps/nginx/conf/nginx.conf
12 ---> Using cache
13 ---> ff665ea05f69
14Step 5/8 : ADD suosuoli.tar.gz /data/nginx/html
15 ---> Using cache
16 ---> dd367b0be1b3
17Step 6/8 : RUN groupadd -g 2019 nginx &&     useradd -g nginx -s /usr/sbin/nologin -u 2019 nginx &&     chown -R nginx.nginx /apps/nginx /data/nginx
18 ---> Using cache
19 ---> 67c4a641d0f8
20Step 7/8 : EXPOSE 80 443
21 ---> Using cache
22 ---> 9747a7021fdd
23Step 8/8 : CMD ["nginx"]
24 ---> Using cache
25 ---> ce5d71aaf355
26Successfully built ce5d71aaf355
27Successfully tagged nginx-ubunt:v1

由于之前构建过,所以都使用了 cache。

5.3 准备 tomcat 镜像

5.3.1 镜像上下文

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/web/tomcat# pwd
 2/opt/dockerfile/dockerfile-example/web/tomcat
 3root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/web/tomcat# ll tomcat-app1/
 4total 24
 5drwxr-xr-x 3 root root 4096 Feb 20 14:18 ./
 6drwxr-xr-x 4 root root 4096 Feb 20 13:35 ../
 7drwxr-xr-x 2 root root 4096 Feb 20 13:54 app1/
 8-rwxr--r-- 1 root root   51 Feb 20 13:56 docker_build_cmd.sh*
 9-rw-r--r-- 1 root root  491 Feb 20 13:56 Dockerfile
10-rwxr-xr-x 1 root root  198 Feb 20 14:18 run_tomcat.sh*
11

5.3.2 构建

 1root@ubuntu-suosuoli-node1:/opt/dockerfile/dockerfile-example/web/tomcat# ./docker_build_cmd.sh
 2Sending build context to Docker daemon  9.726MB
 3Step 1/11 : FROM jdk-base:v8.241
 4 ---> d024ec787a4f
 5Step 2/11 : LABEL author="lisuo"       personal_site="www.suosuoli.cn"       contact="stvobs@163.com"
 6 ---> Using cache
 7 ---> 057c65610c25
 8Step 3/11 : ENV TZ "Asia/Shanghai"
 9 ---> Using cache
10 ---> 333346e4d836
11Step 4/11 : ENV LANG en_US.UTF-8
12 ---> Using cache
13 ---> f11866983f76
14Step 5/11 : ENV TOMCAT_MAJOR_VERSION 8
15 ---> Using cache
16 ---> c4ebfee765a0
17Step 6/11 : ENV TOMCAT_MINOR_VERSION 5.42
18 ---> Using cache
19 ---> aed0454ea780
20Step 7/11 : ENV CATALINA_HOME /apps/tomcat
21 ---> Using cache
22 ---> 36c8238a5aff
23Step 8/11 : ENV APP_DIR ${CATALINA_HOME}/webapps
24 ---> Using cache
25 ---> d90c45859526
26Step 9/11 : RUN mkdir /apps
27 ---> Using cache
28 ---> 6487926fb016
29Step 10/11 : ADD apache-tomcat-8.5.42.tar.gz /apps
30 ---> Using cache
31 ---> 5bf1f8919814
32Step 11/11 : RUN ln -sv /apps/apache-tomcat-8.5.42 /apps/tomcat
33 ---> Using cache
34 ---> 6533b305cfc0
35Successfully built 6533b305cfc0
36Successfully tagged tomcat-base:v8.5.42

由于之前构建过,所以都使用了 cache。

5.4 准备 compose 文件和配置文件

5.4.1 准备 compose 文件

 1root@ubuntu-suosuoli-node1:/data/compose# cat nginx-tomcat-compose.yaml
 2service-haproxy:
 3  image: haproxy-ubuntu:v1
 4  container_name: haproxy-v1
 5  expose:
 6    - 80
 7    - 443
 8    - 9999
 9  ports:
10    - "80:80"
11    - "443:443"
12    - "9999:9999"
13  links:
14    - service-nginx
15
16service-nginx:
17  image: nginx:compiled_V1
18  container_name: nginx-web
19  volumes:
20    - /data/nginx/suosuoli:/usr/local/nginx/html/suosuoli
21    - /data/nginx/static:/usr/local/nginx/html/static
22  expose:
23    - 80
24    - 443
25      #  ports:
26      #    - "8800:80"
27      #    - "8443:443"
28
29  links:
30    - service-tomcat-app1
31    - service-tomcat-app2
32
33service-tomcat-app1:
34  image: tomcat-business:app1
35  container_name: tomcat-app1
36  volumes:
37    - /data/tomcat/webapps/suosuoli:/apps/tomcat/webapps/
38  expose:
39    - 8080
40      #  ports:
41      #    - "8081:8080"
42
43service-tomcat-app2:
44  image: tomcat-business:app2
45  container_name: tomcat-app2
46  volumes:
47    - /data/tomcat/webapps/suosuoli:/apps/tomcat/webapps/
48  expose:
49    - 8080
50      #  ports:
51      #    - "8082:8080"

5.4.2 准备 nginx 静态文件

1root@ubuntu-suosuoli-node1:~# cd /data/nginx/static/
2root@ubuntu-suosuoli-node1:/data/nginx/static# rz
3
4root@ubuntu-suosuoli-node1:/data/nginx/static# ll
5total 40
6drwxr-xr-x 2 root root  4096 Feb 29 13:23 ./
7drwxr-xr-x 4 root root  4096 Feb 29 13:20 ../
8-rw-r--r-- 1 root root 30470 Oct 25 08:06 amazed.png
9root@ubuntu-suosuoli-node1:/data/nginx/static# vim index.html
 1<!DOCTYPE html>
 2<html lang="en">
 3  <head>
 4    <meta charset="UTF-8" />
 5    <title>js_start</title>
 6    <h1 id="h">Hello, this is a js test message...</h1>
 7  </head>
 8  <body>
 9    <canvas
10      id="myCanvas"
11      width="600"
12      height="400"
13      style="border: 8px solid #009"
14    ></canvas>
15    <script>
16                                  const canvas = document.getElementById("myCanvas");
17      const context = canvas.getContext("2d");
18
19      let x = 50;
20      let y = 50;
21
22      let xChange = 0.6;
23      let yChange = 0.3;
24
25      function blob(xloc, yloc, sizeroke();
26
27                          if (x >= canvas.width - 40|| x <= 40) {
28                                                  xChange *= -1;
29                                              }
30
31                          if (y >= canvas.height - 40|| y <= 40) {
32                                                  yChange *= -1;
33                                              }
34
35                          x += xChange;
36                          y += yChange; }
37
38          setInterval(function () {
39                                 blob(x, y, 40, "green")
40
41                              }, 1);
42
43
44      document.getElementById("mod").value = "click";
45    </script>
46  </body>
47</html>

5.4.3 准备 nginx.conf 文件

 1user  nginx;
 2worker_processes  1;
 3daemon off;
 4error_log  logs/error.log  notice;
 5pid        logs/nginx.pid;
 6events {
 7    worker_connections  1024;
 8}
 9http {
10    include       mime.types;
11    default_type  application/octet-stream;
12    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
13                      '$status $body_bytes_sent "$http_referer" '
14                      '"$http_user_agent" "$http_x_forwarded_for"';
15upstream tomcat_server {
16    server service-tomcat-app1:8080;
17    server service-tomcat-app2:8080;
18}
19    access_log  logs/access.log  main;
20    sendfile        on;
21    keepalive_timeout  65;
22    server {
23        listen       80;
24        server_name  localhost;
25        access_log  logs/host.access.log  main;
26        location / {
27            root   html;
28            index  index.html index.htm;
29        }
30        location /suosuoli {
31        root /usr/local/nginx/html;
32        index index.html
33}
34
35        location /app {
36        proxy_pass http://tomcat_server;
37        proxy_set_header   Host    $host;
38        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
39        proxy_set_header   X-Real-IP $remote_addr;
40
41
42}
43        error_page   500 502 503 504  /50x.html;
44        location = /50x.html {
45            root   html;
46        }
47    }
48}

5.4.4 准备 tomcat 页面

1root@ubuntu-suosuoli-node1:~# mkdir -pv /data/tomcat/webapps/suosuoli
2root@ubuntu-suosuoli-node1:~# cd /data/tomcat/webapps/suosuoli
3root@ubuntu-suosuoli-node1:/data/tomcat/webapps/suosuoli# vim host-info.jsp
 1<%@page import="java.util.Enumeration"%>
 2<br />
 3host: <%try{out.println(""+java.net.InetAddress.getLocalHost().getHostName());}catch(Exception e){}%>
 4<br />
 5remoteAddr: <%=request.getRemoteAddr()%>
 6<br />
 7remoteHost: <%=request.getRemoteHost()%>
 8<br />
 9sessionId: <%=request.getSession().getId()%>
10<br />
11serverName:<%=request.getServerName()%>
12<br />
13scheme:<%=request.getScheme()%>
14<br />
15<%request.getSession().setAttribute("t1","t2");%>
16<%
17        Enumeration en = request.getHeaderNames();
18        while(en.hasMoreElements()){
19        String hd = en.nextElement().toString();
20                out.println(hd+" : "+request.getHeader(hd));
21        out.println("<br />");
22        }
23%>

5.4.5 启动容器

1root@ubuntu-suosuoli-node1:/data/tomcat/webapps/suosuoli# cd  /data/compose/
2root@ubuntu-suosuoli-node1:/data/compose# docker-compose -f nginx-tomcat-compose.yaml up -d
3Creating tomcat-app2 ... done
4Creating tomcat-app1 ... done
5Creating nginx-web   ... done
6Creating haproxy-v1  ... done

5.5 验证容器是否启动

 1root@ubuntu-suosuoli-node1:/data/compose# docker-compose ps
 2   Name                  Command               State                                Ports
 3-----------------------------------------------------------------------------------------------------------------------
 4haproxy-v1    /usr/bin/run_haproxy.sh          Up      0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp, 0.0.0.0:9999->9999/tcp
 5nginx-web     nginx                            Up      443/tcp, 80/tcp
 6tomcat-app1   /apps/tomcat/bin/run_tomcat.sh   Up      8005/tcp, 8009/tcp, 8080/tcp
 7tomcat-app2   /apps/tomcat/bin/run_tomcat.sh   Up      8005/tcp, 8009/tcp, 8080/tcp
 8
 9
10root@ubuntu-suosuoli-node1:/data/compose# docker ps
11CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                                                              NAMES
1233cc1026bbc6        haproxy-ubuntu:v1      "/usr/bin/run_haprox…"   20 minutes ago      Up 20 minutes       0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:9999->9999/tcp   haproxy-v1
13994b9226d1b3        nginx-ubunt:v1         "nginx"                  20 minutes ago      Up 4 minutes        80/tcp, 443/tcp                                                    nginx-web
14e601c88b1e45        tomcat-business:app1   "/apps/tomcat/bin/ru…"   20 minutes ago      Up 20 minutes       8005/tcp, 8009/tcp, 8080/tcp                                       tomcat-app1
1559008c4131cf        tomcat-business:app2   "/apps/tomcat/bin/ru…"   20 minutes ago      Up 20 minutes       8005/tcp, 8009/tcp, 8080/tcp                                       tomcat-app2root@ubuntu-suosuoli-node1:/data/compose# docker ps
16CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                                                              NAMES
1733cc1026bbc6        haproxy-ubuntu:v1      "/usr/bin/run_haprox…"   20 minutes ago      Up 20 minutes       0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:9999->9999/tcp   haproxy-v1
18994b9226d1b3        nginx-ubunt:v1         "nginx"                  20 minutes ago      Up 4 minutes        80/tcp, 443/tcp                                                    nginx-web
19e601c88b1e45        tomcat-business:app1   "/apps/tomcat/bin/ru…"   20 minutes ago      Up 20 minutes       8005/tcp, 8009/tcp, 8080/tcp                                       tomcat-app1
2059008c4131cf        tomcat-business:app2   "/apps/tomcat/bin/ru…"   20 minutes ago      Up 20 minutes       8005/tcp, 8009/tcp, 8080/tcp                                       tomcat-app2

5.6 查看启动日志

 1root@ubuntu-suosuoli-node1:/data/compose# docker-compose logs -f
 2Attaching to haproxy-v1, nginx-web, tomcat-app1, tomcat-app2
 3haproxy-v1             | 127.0.0.1	localhost
 4haproxy-v1             | ::1	localhost ip6-localhost ip6-loopback
 5haproxy-v1             | fe00::0	ip6-localnet
 6haproxy-v1             | ff00::0	ip6-mcastprefix
 7haproxy-v1             | ff02::1	ip6-allnodes
 8haproxy-v1             | ff02::2	ip6-allrouters
 9haproxy-v1             | 172.17.0.4	nginx-web 01870c340091
10haproxy-v1             | 172.17.0.4	service-nginx 01870c340091 nginx-web
11haproxy-v1             | 172.17.0.5	932d6c63f681
12tomcat-app1            | Tomcat started.
13tomcat-app1            | 127.0.0.1	localhost
14tomcat-app1            | ::1	localhost ip6-localhost ip6-loopback
15tomcat-app1            | fe00::0	ip6-localnet
16tomcat-app1            | ff00::0	ip6-mcastprefix
17tomcat-app1            | ff02::1	ip6-allnodes
18tomcat-app1            | ff02::2	ip6-allrouters
19tomcat-app1            | 172.17.0.3	8b9f99ba5279
20tomcat-app1            | 192.168.100.18 test.suosuoli.cn
21tomcat-app2            | Tomcat started.
22tomcat-app2            | # Third party programs must not access this file directly, but only through the
23tomcat-app2            | # symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
24tomcat-app2            | # replace this symlink by a static file or a different symlink.
25tomcat-app2            | #
26tomcat-app2            | # See man:systemd-resolved.service(8) for details about the supported modes of
27tomcat-app2            | # operation for /etc/resolv.conf.
28tomcat-app2            |
29tomcat-app2            | nameserver 192.168.100.2
30tomcat-app2            | search localdomain
31tomcat-app2            | nameserver 223.6.6.6

5.7 访问测试

5.7.1 访问 haproxy

5.7.2 访问 nginx 静态页面

5.7.3 访问 tomcat 静态页面

5.7.4 访问 tomcat 动态页面


Docker基础
Docker镜像构建和使用