【Docker】Docker学习⑨ - 单机编排之Docker Compose

【Docker】Docker学习⑨ - 单机编排之Docker Compose

  • 一、Docker简介
  • 二、Docker安装及基础命令介绍
  • 三、Docker镜像管理
  • 四、Docker镜像与制作
  • 五、Docker数据管理
  • 六、网络部分
  • 七、Docker仓库之单机Dokcer Registry
  • 八、Docker仓库之分布式Harbor
  • 九、单机编排之Docker Compose
    • 1 基础环境准备
    • 2 从docker compose启动单个容器
    • 3 从docker compose启动多个容器
    • 4 定义数据卷挂载
    • 5 实现单机版的HA+NGINX+TOMCAT
      • 5.1 制作haproxy镜像
      • 5.2 准备nginx镜像
      • 5.3 准备tomcat镜像
      • 5.4 编辑docker compose 文件及环境准备
      • 5.5 启动容器

一、Docker简介

  • 参考:【Docker】Dokcer学习① - 简介

二、Docker安装及基础命令介绍

  • 参考:【Docker】Docker学习② - Docker安装及基础命令介绍

三、Docker镜像管理

  • 参考:【Docker】Docker学习③ - Docker镜像管理

四、Docker镜像与制作

  • 参考:【Docker】Docker学习④ - Docker镜像与制作

五、Docker数据管理

  • 参考:【Docker】Docker学习⑤ - Docker数据管理

六、网络部分

  • 参考:【Docker】Docker学习⑥ - 网络部分

七、Docker仓库之单机Dokcer Registry

  • 参考:【Docker】Docker学习⑦ - Docker仓库之单机Dokcer Registry

八、Docker仓库之分布式Harbor

  • 参考:【Docker】Docker学习⑧ - Docker仓库之分布式Harbor

九、单机编排之Docker Compose

当在宿主机启动较多的容器的时候,如果都是手动操作会觉得比较麻烦而且容易出错,这个时候推荐使用docker单机编排工具docker compose,Dokcer Compose是docker容器的一种编排服务,docker compose是一个管理多个容器的工具,比如可以解决容器之间的依赖关系,就像启动一个web就必须得先把数据库服务先启动一样,docker compose完全可以替代docker run启动容器。

  • github地址:https://github.com/docker/compose

1 基础环境准备

  • 1.1 安装python环境及pip命令
	yum install https://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm -y
	yum install python-pip -y
	pip install --upgrade pip 
  • 1.2 安装docker compose
	pip install docker-compose
  • 1.3 验证版本
	docker-compose version

日志:

	[root@gbase8c_private ~]# docker-compose version
	/usr/lib/python2.7/site-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
	from cryptography.hazmat.backends import default_backend
	docker-compose version 1.26.2, build unknown
	docker-py version: 4.4.4
	CPython version: 2.7.5
	OpenSSL version: OpenSSL 1.0.2k-fips  26 Jan 2017
  • 1.4 查看帮助
	docker-compose --help
	[root@gbase8c_private ~]# docker-compose --help
	/usr/lib/python2.7/site-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
	from cryptography.hazmat.backends import default_backend
	Define and run multi-container applications with Docker.
	
	Usage:
	docker-compose [-f ...] [options] [COMMAND] [ARGS...]
	docker-compose -h|--help
	
	Options:
	-f, --file FILE             Specify an alternate compose file
								(default: docker-compose.yml)
	-p, --project-name NAME     Specify an alternate project name
								(default: directory name)
	-c, --context NAME          Specify a context name
	--verbose                   Show more output
	--log-level LEVEL           Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
	--no-ansi                   Do not print ANSI control characters
	-v, --version               Print version and exit
	-H, --host HOST             Daemon socket to connect to
	
	--tls                       Use TLS; implied by --tlsverify
	--tlscacert CA_PATH         Trust certs signed only by this CA
	--tlscert CLIENT_CERT_PATH  Path to TLS certificate file
	--tlskey TLS_KEY_PATH       Path to TLS key file
	--tlsverify                 Use TLS and verify the remote
	--skip-hostname-check       Don't check the daemon's hostname against the
								name specified in the client certificate
	--project-directory PATH    Specify an alternate working directory
								(default: the path of the Compose file)
	--compatibility             If set, Compose will attempt to convert keys
								in v3 files to their non-Swarm equivalent
	--env-file PATH             Specify an alternate environment file
	
	Commands:
	build              Build or rebuild services
	config             Validate and view the Compose file
	create             Create services
	down               Stop and remove containers, networks, images, and volumes
	events             Receive real time events from containers
	exec               Execute a command in a running container
	help               Get help on a command
	images             List images
	kill               Kill containers
	logs               View output from containers
	pause              Pause services
	port               Print the public port for a port binding
	ps                 List containers
	pull               Pull service images
	push               Push service images
	restart            Restart services
	rm                 Remove stopped containers
	run                Run a one-off command
	scale              Set number of containers for a service
	start              Start services
	stop               Stop services
	top                Display the running processes
	unpause            Unpause services
	up                 Create and start containers
	version            Show the Docker-Compose version information

2 从docker compose启动单个容器

目录可以在任意目录,推荐放在有意义的位置(/usr/local/docker-compos)

  • 2.1 一个容器的docker compose文件
    设置一个yml格式的配置文件,因此要注意前后缩进
	vim /usr/local/docker-compos/docker-compose.yml
	[root@gbase8c_private docker-compose]# cat docker-compose.yml 
	web1:
	image: 192.168.56.199/nginx/nginx:v1
	expose:
		- 80
		- 443
	ports:
		- "80:80"
		- "443:443"
  • 2.2 启动容器
    必须要在docker compose文件所在的目录执行:
	docker-compose up #前台启动
	[root@gbase8c_private docker-compose]# docker-compose up
	/usr/lib/python2.7/site-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
	from cryptography.hazmat.backends import default_backend
	Creating docker-compose_web1_1 ... done
	Attaching to docker-compose_web1_1
	web1_1  | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
	web1_1  | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
	web1_1  | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
	web1_1  | 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
	web1_1  | 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
	web1_1  | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
	web1_1  | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
	web1_1  | /docker-entrypoint.sh: Configuration complete; ready for start up
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: using the "epoll" event method
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: nginx/1.21.5
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: OS: Linux 3.10.0-1160.71.1.el7.x86_64
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: start worker processes
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: start worker process 29
	web1_1  | 2023/12/17 14:41:21 [notice] 1#1: start worker process 30
	^CGracefully stopping... (press Ctrl+C again to force)
	Stopping docker-compose_web1_1 ... done
  • 2.3 web访问测试
  • 2.4 后台启动服务
    容器在启动的时候,会给容器自定义一个名称
	docker-compose up -d

日志:

	[root@gbase8c_private docker-compose]# docker-compose up -d
	Starting docker-compose_web1_1 ... done  #容器名称
  • 2.5 自定义容器名称
	[root@gbase8c_private docker-compose]# cat docker-compose.yml 
web1:
  image: 192.168.56.199/nginx/nginx:v1
  expose:
    - 80
    - 443
  container_name: nginx-web1   #自定义容器名称
  ports:
    - "80:80"
    - "443:443"

日志:

	[root@gbase8c_private docker-compose]# docker-compose stop
	Stopping docker-compose_web1_1 ... done
	[root@gbase8c_private docker-compose]# docker ps -a
	CONTAINER ID        IMAGE                                      COMMAND                  CREATED             STATUS                      PORTS               NAMES
	72aed697d033        192.168.56.199/nginx/nginx:v1              "/docker-entrypoint.…"   9 minutes ago       Exited (0) 13 seconds ago                       docker-compose_web1_1
	[root@gbase8c_private docker-compose]# docker-compose up -d
	Recreating docker-compose_web1_1 ... done
	[root@gbase8c_private docker-compose]# docker ps -a
	CONTAINER ID        IMAGE                                      COMMAND                  CREATED             STATUS                    PORTS                                      NAMES
	f1033c073624        192.168.56.199/nginx/nginx:v1              "/docker-entrypoint.…"   2 seconds ago       Up 2 seconds              0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   nginx-web1
	[root@gbase8c_private docker-compose]# 

3 从docker compose启动多个容器

  • 3.1 编辑docker-compose文件
	cat docker-compose.yml
web1:
  image: 192.168.56.199/nginx/nginx:v1
  expose:
    - 80
    - 443
  container_name: nginx-web1 
  ports:
    - "80:80"
    - "443:443"
web2:  #每个容器一个ID
  image: 192.168.56.199/nginx/nginx:v1
  expose:
    - 80
    - 443
  container_name: nginx-web2 
  ports:
    - "81:80"
    - "444:443"

日志:

	[root@gbase8c_private docker-compose]# docker-compose stop
	Stopping nginx-web1 ... done
	[root@gbase8c_private docker-compose]# docker ps -a
	CONTAINER ID        IMAGE                                      COMMAND                  CREATED             STATUS                     PORTS               NAMES
	f1033c073624        192.168.56.199/nginx/nginx:v1              "/docker-entrypoint.…"   5 minutes ago       Exited (0) 6 seconds ago                       nginx-web1
	[root@gbase8c_private docker-compose]# docker-compose up -d
	Starting nginx-web1 ... done
	Creating nginx-web2 ... done
	[root@gbase8c_private docker-compose]# docker ps
	CONTAINER ID        IMAGE                           COMMAND                  CREATED             STATUS              PORTS                                      NAMES
	341ed2cbd17d        192.168.56.199/nginx/nginx:v1   "/docker-entrypoint.…"   51 seconds ago      Up 50 seconds       0.0.0.0:81->80/tcp, 0.0.0.0:444->443/tcp   nginx-web2
	f1033c073624        192.168.56.199/nginx/nginx:v1   "/docker-entrypoint.…"   6 minutes ago       Up 50 seconds       0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   nginx-web1
  • 3.2 web访问测试

4 定义数据卷挂载

  • 4.1 创建数据目录和文件
mkdir -p /data/nginx
echo "Test Nginx Volume" > /data/nginx/index.html
  • 4.2 编辑compose配置文件
cat docker-compose.yml
web1:
  image: jack/nginx-1.22.1:v1
  expose:
    - 80
    - 443
  container_name: nginx-web1 
  volumes:
    - /data/nginx:/usr/local/nginx/html
  ports:
    - "80:80"
    - "443:443"
web2:  #每个容器一个ID
  image: jack/nginx-1.22.1:v1
  expose:
    - 80
    - 443
  container_name: nginx-web2 
  ports:
    - "81:80"
    - "444:443"
  • 4.3 重启容器
docker-compose stop
docker-compose up -d
  • 4.4 登录验证Web访问

  • 4.5 其他常用命令

##重启单个指定容器
docker-compose restart web1
##重启所有容器
docker-compose restart
##停止和启动单个容器
docker-compose stop web1
docker-compose start web1
##停止和启动所有容器
docker-compose stop
docker-compose start

5 实现单机版的HA+NGINX+TOMCAT

5.1 制作haproxy镜像

  • 5.1.1 编辑Dockerfile文件
cd /opt/dockerfile/web/haproxy
cat Dockerfile
#My Dockerfile
From docker.io/centos:latest
MAINTAINER chengk "[email protected]"

#Yum Setting
RUN rpm -ivh http://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm
#以下为centos8需要
RUN sed -i -e "s|mirrorlist=|#mirrorlist=|g" /etc/yum.repos.d/CentOS-*
RUN sed -i -e "s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g" /etc/yum.repos.d/CentOS-*

RUN yum install gcc gcc-c++ pcre pcre-devel openssl openssl-devel make vim wget tree lrzsz  automake  zlib zlib-devel  iproute net-tools iotop -y
ADD haproxy-1.8.31.tar.gz /usr/local/src/
RUN cd /usr/local/src/haproxy-1.8.31 && make TARGET=linux2628 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 PREFIX=/usr/local/haproxy && make install PREFIX=/usr/local/haproxy
RUN cp /usr/local/src/haproxy-1.8.31/examples/haproxy.init  /etc/init.d/haproxy
RUN cp /usr/local/src/haproxy-1.8.31/haproxy /usr/sbin/haproxy
ADD haproxy.service /usr/lib/systemd/system/haproxy.service
ADD haproxy /etc/sysconfig/haproxy
ADD run_haproxy.sh /root/script/run_haproxy.sh
ADD haproxy.cfg /etc/haproxy/haproxy.cfg
RUN chmod a+x /root/script/run_haproxy.sh

CMD ["/root/script/run_haproxy.sh"]
EXPOSE 80 9999
  • 5.1.2 准备服务启动脚本
cat haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target
SourcePath=/etc/init.d/haproxy
[Service]
EnvironmentFile=/etc/sysconfig/haproxy
ExecStart=/etc/init.d/haproxy start
ExecStop=/etc/init.d/haproxy stop
ExecReload=/etc/init.d/haproxy reload

[Install]
WantedBy=multi-user.target
  • 5.1.3 前台启动脚本
cat run_haproxy.sh
#!/bin/bash
/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
tail -f /etc/hosts
  • 5.1.4 haproxy参数文件
cat haproxy
OPTIONS=""
  • 5.1.5 准备压缩包及其他文件
-rw-r--r-- 1 root root     858 1月  19 20:04 Dockerfile
-rw-r--r-- 1 root root     301 1月  19 20:05 haproxy.service
-rw-r--r-- 1 root root      94 1月  19 20:05 run_haproxy.sh
-rw-r--r-- 1 root root      11 1月  19 20:05 haproxy
-rw-r--r-- 1 root root    2523 1月  19 20:06 CentOS-Base.repo
-rw-r--r-- 1 root root     951 1月  19 20:06 epel.repo
-rw-r--r-- 1 root root 2219503 1月  19 20:07 haproxy-1.8.31.tar.gz
  • 5.1.6 执行构建镜像
docker build -t 192.168.56.199/centos/centos_haproxy_1.8.31 /opt/dockerfile/web/haproxy/
docker rm -f `docker ps -a -q`
docker rmi 192.168.56.199/centos/centos_haproxy_1.8.31:v1
docker tag 192.168.56.199/centos/centos_haproxy_1.8.31:latest 192.168.56.199/centos/centos_haproxy_1.8.31:v1

5.2 准备nginx镜像

5.3 准备tomcat镜像

5.4 编辑docker compose 文件及环境准备

  • 5.4.1 编辑docker compose文件
cat docker-compose.yml
nginx-web1:
  image: jack/nginx-1.22.1:v1
  expose:
    - 80
    - 443
  container_name: nginx-web1 
  volumes:
    - /data/nginx:/usr/local/nginx/html
    - /usr/local/nginx/conf/nginx.conf:/usr/local/nginx/conf/nginx.conf
  links:
    - tomcat-web1
    - tomcat-web2
nginx-web2:  
  image: jack/nginx-1.22.1:v1
  expose:
    - 80
    - 443
  container_name: nginx-web2 
  volumes:
        - /usr/local/nginx/conf/nginx.conf:/usr/local/nginx/conf/nginx.conf
  links:
    - tomcat-web1
    - tomcat-web2
tomcat-web1:
  container_name: tomcat-web1
  image: tomcat-web:app1
  user: root
  command: /apps/tomcat/bin/run_tomcat.sh
  volumes: 
    - /apps/tomcat/webapps/SalesManager:/apps/tomcat/webapps/SalesManager
  expose:
    - 8080
    - 8443
tomcat-web2:
  container_name: tomcat-web2
  image: tomcat-web:app1
  user: root
  command: /apps/tomcat/bin/run_tomcat.sh
  volumes: 
    - /apps/tomcat/webapps/SalesManager:/apps/tomcat/webapps/SalesManager
  expose:
    - 8080
    - 8443
haproxy-web1:
  container_name: haproxy-web1
  image: 192.168.56.199/centos/centos_haproxy_1.8.31:v1
  command: /root/script/run_haproxy.sh
  volumes:
    - /etc/haproxy/haproxy.cfg:/etc/haproxy/haproxy.cfg
  ports:
    - "9999:9999"
    - "80:80"
  links:
    - nginx-web1
    - nginx-web2
  • 5.4.2 准备nginx静态页面
cat /data/nginx/index.html
Test Nginx Volme
  • 5.4.3 准备nginx 配置文件
#本地路径和nginx路径都是/usr/local/nginx/conf/nginx.conf
grep -v "#" /usr/local/nginx/conf/nginx.conf
user nginx;
worker_processes auto;
daemon off;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
	upstream tomcat_webserver{
	    server tomcat-web1:8080;
		server tomcat-web2:8080;
	}
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
		location /SalesManager {
		    proxy_pass http://tomcat_webserver;
			proxy_set_header Host $host;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header X-Real-IP $remote_addr;	
		}
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
  • 5.4.4 准备tomcat页面文件
ll /apps/tomcat/webapps/SalesManager
cat /apps/tomcat/webapps/SalesManager/showhost.jsp
<%@page import="java.util.Enumeration"%>

host:<%try{out.println(""+java.net.InetAddress.getLocalHost().getHostName());}catch(Exception e){}%>
<%request.getSession().setAttribute("t1","t2");%> <% Enumeration en = request.getHeaderNames(); while(en.hasMoreElements()){ String hd = en.nextElement().toString(); out.println(hd+":"+request.getHeader(hd)); out.println("
"); } %>

5.5 启动容器

日志:

	[root@gbase8c_private docker-compose]# docker-compose up -d
	/usr/lib/python2.7/site-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
	from cryptography.hazmat.backends import default_backend
	Creating tomcat-web1 ... done
	Creating tomcat-web2 ... done
	Creating nginx-web2  ... done
	Creating nginx-web1  ... done
	Creating haproxy-web1 ... done
	[root@gbase8c_private docker-compose]# docker ps -a
	CONTAINER ID        IMAGE                                            COMMAND                  CREATED             STATUS              PORTS                                        NAMES
	679cadcf5244        192.168.56.199/centos/centos_haproxy_1.8.31:v1   "/root/script/run_ha…"   5 seconds ago       Up 4 seconds        0.0.0.0:80->80/tcp, 0.0.0.0:9999->9999/tcp   haproxy-web1
	d7bd6746c7ee        jack/nginx-1.22.1:v1                             "nginx"                  6 seconds ago       Up 4 seconds        80/tcp, 443/tcp                              nginx-web1
	fb3df1f58075        jack/nginx-1.22.1:v1                             "nginx"                  6 seconds ago       Up 4 seconds        80/tcp, 443/tcp                              nginx-web2
	f0d87107431b        tomcat-web:app1                                  "/apps/tomcat/bin/ru…"   7 seconds ago       Up 5 seconds        8009/tcp, 8080/tcp, 8443/tcp                 tomcat-web2
	6424d08ff212        tomcat-web:app1                                  "/apps/tomcat/bin/ru…"   7 seconds ago       Up 5 seconds        8009/tcp, 8080/tcp, 8443/tcp                 tomcat-web1
	[root@gbase8c_private docker-compose]# docker-compose logs -f
	/usr/lib/python2.7/site-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
	from cryptography.hazmat.backends import default_backend
	Attaching to haproxy-web1, nginx-web1, nginx-web2, tomcat-web2, tomcat-web1
	tomcat-web1     | Tomcat started.
	tomcat-web1     | 127.0.0.1	localhost
	tomcat-web1     | ::1	localhost ip6-localhost ip6-loopback
	tomcat-web1     | fe00::0	ip6-localnet
	tomcat-web1     | ff00::0	ip6-mcastprefix
	tomcat-web1     | ff02::1	ip6-allnodes
	tomcat-web1     | ff02::2	ip6-allrouters
	tomcat-web1     | 10.10.0.2	6424d08ff212
	tomcat-web1     | 1.1.1.1 abc.test.com
	haproxy-web1    | 127.0.0.1	localhost
	haproxy-web1    | ::1	localhost ip6-localhost ip6-loopback
	haproxy-web1    | fe00::0	ip6-localnet
	haproxy-web1    | ff00::0	ip6-mcastprefix
	tomcat-web2     | Tomcat started.
	haproxy-web1    | ff02::1	ip6-allnodes
	haproxy-web1    | ff02::2	ip6-allrouters
	tomcat-web2     | 127.0.0.1	localhost
	haproxy-web1    | 10.10.0.5	nginx-web1 d7bd6746c7ee
	haproxy-web1    | 10.10.0.4	nginx-web2 fb3df1f58075
	haproxy-web1    | 10.10.0.6	679cadcf5244
	tomcat-web2     | ::1	localhost ip6-localhost ip6-loopback
	tomcat-web2     | fe00::0	ip6-localnet
	tomcat-web2     | ff00::0	ip6-mcastprefix
	tomcat-web2     | ff02::1	ip6-allnodes
	tomcat-web2     | ff02::2	ip6-allrouters
	tomcat-web2     | 10.10.0.3	f0d87107431b
	tomcat-web2     | 1.1.1.1 abc.test.com

你可能感兴趣的:(docker,学习,容器)