Docker学习记录

Docker

安装

# 安装gcc相关环境
yum -y install gcc
yum -y install gcc-c++
## 卸载旧版本
yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
# 安装
yum install -y yum-utils
yum-config-manager \
    --add-repo \
    https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum makecache fast

ce 社区版 ee 企业版

yum install docker-ce[docker-ee] docker-ce-cli[docker-ee-cli] containerd.io docker-compose-plugin

安指定版本

yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io docker-compose-plugin

卸载

sudo yum remove docker-ce docker-ce-cli containerd.io docker-compose-plugin
sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd

启动

systemctl start/stop/status/enable/disable docker

命令

查版本/查信息

docker version/info

设置阿里云加速

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://todnba9t.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

镜像相关命令

查看全部镜像 [-a 全部; -q 只ID]

docker images [-aq]

hub上搜索镜像 [过滤*大于等于1000的]

docker search mysql [-f stars=1000]

hub上拉取镜像 [指定版本 默认last]

docker pull mysql[:5.7]

删除指定镜像 [删除多个]

docker rmi -f 镜像ID [镜像ID 镜像ID]

删除所有镜像

docker rmi -f $(docker images -aq)

容器相关命令

交互方式运行镜像

docker run [参数] image
	# --name="名字"		# 指定容器名字
	# -d					# 后台运行
	# -it					# 交互方式运行并进入容器
	# -p					# 指定端口
	# 	-p # ip:主机端口:容器端口  配置主机端口映射到容器端口
	# 	-p # 主机端口:容器端口
	# 	-p # 容器端口
	# -P					# 随机指定端口
	# eg: docker run -it centos /bin/bash 	

退出容器并停止 Ctrl+P+Q 不停止退出

exit

列出运行中容器 [全部带历史 ][只ID][最近创建的两个]

docker ps [-a][-q][-n=2]

删除指定的容器,不能删除正在运行的容器,强制删除使用 rm -f

docker rm 容器ID

删除全部

docker rm -f $(docker ps -aq)

启动停止重启杀死

docker start/stop/restart/kill 容器ID

其他

查看日志

docker logs -tf 容器ID
#num为要显示的日志条数
docker logs --tail num 容器ID 

看容器进程信息

docker top 容器ID

看容器元数据信息

docker inspect 容器id

进入容器

docker exec 容器ID # 进入容器后开启一个新的终端,可以在里面操作 docker exec -it bd2a1db199b7 /bin/bash
docker attach 容器ID # 进入容器正在执行的终端,不会启动新的进程 docker attach bd2a1db199b7

拷贝容器文件到主机

docker cp 容器id:/容器内路径 目的主机路径 # docker cp bd2a1db199b7:/home/test.java /home

查看容器cpu信息

docker stats

docker 安装 nginx

docker search nginx
docker pull nginx
docker run --name nginx01 -d -p 3344:80 nginx

docker 安装 tomcat

docker pull tomcat:9.0
docker run -it --rm tomcat:9.0  ##直接启动关闭就删除 测试用
docker run --name tomcat01 -d -p 3344:8080 tomcat:9.0

docker 安装 es+kibana

docker run -d --name es01 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.3.0

docker 安装 mysql

docker pull mysql:5.7
docker run -d -p 3310:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql mysql:5.7

打包自己的镜像

docker commit -a="wendy" -m="tomcat with root page" 027db740109a tomcat8-with-root-page:1.0

容器卷

容器卷挂载

##本机路径:容器路径  docker inspect 容器id  中Mounts块查看挂载是否成功
docker run -it -v /home/share:/home centos
	# -v 容器内路径 							# 匿名挂载  -v /etc/nginx
	# -v 卷名:容器内路径					  # 具名挂载  -v juming:/etc/nginx
	# -v /宿主机路径:容器内路径  			   # 指定路径挂载  -v /home/nginx:/etc/nginx
	# -v 路径:路径:ro/rw  	 # 指定权限(ro->readonly rw->readwrite) -v juming:/etc/nginx:ro

查看挂载信息

# 查看匿名/具名挂载卷 [详情,具体哪个目录][删全部][删一个][新建]
docker volume ls [inspect 名字][prune][rm][create]
[root@localhost /]# docker volume ls
DRIVER              VOLUME NAME
local               9c234d2dc4b5124fe85a11cc38fe066fd6e6b2d5be90587b0e48c31af91369d4
local               juming
[root@localhost /]# docker volume inspect 9c234d2dc4b5124fe85a11cc38fe066fd6e6b2d5be90587b0e48c31af91369d4

容器间共享卷

# 先启动一个有挂载的容器 ["volume1","volume2"]
docker run -it --name docker01 wendy-centos:1.0 /bin/bash
## --volume-from一个有挂载的容器  就可以实现数据共享 (复制模式共享,删除docker01也不影响docker02)
docker run -it --name docker02 --volume-from docker01 wendy-centos:1.0 /bin/bash

DockerFile

dockerfile 挂载

dockerfile1 文件内容

FROM centos
VOLUME ["volume1","volume2"]  // 匿名挂载
CMD echo "-----end-----"
CMD /bin/bash

构建

docker build -f dockerfile1 -t wendy-centos:1.0 .

构建dockerfile命令

docker build -f dockerfile1 -t wendy-centos:1.0 .

dockerfile 常用指令

FROM 					# 基础镜像,一切从这里构建
MAINTAINER			 	# 镜像是谁写的  名字<邮箱>
RUN						# 镜像构建的时候需要运行的命令
ADD						# 为镜像添加内容(压缩包)
WORKDIR					# 镜像的工作目录
VOLUME					# 挂载目录
EXPOSE					# 暴露端口
CMD						# 指定这个容器启动的时候要运行的命令,只有最后一个会生效,相当替换
ENTRYPOINT				# 指定这个容器启动的时候要运行的命令,追加
ONBUILD					# 当构建一个被集成dockerfile这个时候会运行ONBUILD 触发指令
COPY					# 类似ADD  将我们文件拷贝到镜像中
ENV						# 构建时设置环境变量

初步构建

构建一个含有vim和ifconfig命令的centos

[root@localhost docker-test-v]# cat mydockerfile-centos

FROM centos:7
MAINTAINER wendy<zhiwen.ji@qq.com>

ENV MYPATH /usr/local
WORKDIR $MYPATH

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 8888

CMD echo $MYPATH
CMD echo "-----end-----"

CMD /bin/bash

构建命令

docker build -f mydockerfile-centos -t mydfcentos:0.1 .

正常centos和构建centos对比

正常:

[root@localhost ~]# docker run -it centos:7 /bin/bash
[root@8d051480d5af /]# ls
anaconda-post.log  bin  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@8d051480d5af /]# vim a
bash: vim: command not found
[root@8d051480d5af /]# ifconfig
bash: ifconfig: command not found

构建:

[root@localhost docker-test-v]# docker run -it mydfcentos:0.1 /bin/bash
[root@c26533c126c0 local]# pwd
/usr/local
[root@c26533c126c0 local]# ls
bin  etc  games  include  lib  lib64  libexec  sbin  share  src
[root@c26533c126c0 local]# vim a
[root@c26533c126c0 local]# ls
a  bin  etc  games  include  lib  lib64  libexec  sbin  share  src
[root@c26533c126c0 local]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:03  txqueuelen 0  (Ethernet)
        RX packets 8  bytes 648 (648.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

查看构建步骤历史

# docker history 镜像ID
[root@localhost docker-test-v]# docker history 35c22c10d0f2
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
35c22c10d0f2        13 minutes ago      /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin…   0B                  
34421c0487cf        13 minutes ago      /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B                  
684cecdf472a        13 minutes ago      /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo…   0B                  
1901c612ec6a        13 minutes ago      /bin/sh -c #(nop)  EXPOSE 8888                  0B                  
bece07184685        13 minutes ago      /bin/sh -c yum -y install net-tools             177MB               
f4f90fc61e6d        13 minutes ago      /bin/sh -c yum -y install vim                   232MB               
8f0931e4ba0a        13 minutes ago      /bin/sh -c #(nop) WORKDIR /usr/local            0B                  
113d7c9b5a7b        13 minutes ago      /bin/sh -c #(nop)  ENV MYPATH=/usr/local        0B                  
da8cae163faf        13 minutes ago      /bin/sh -c #(nop)  MAINTAINER wendy<zhiwen.j…   0B                  
eeb6ee3f44bd        10 months ago       /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
<missing>           10 months ago       /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B                  
<missing>           10 months ago       /bin/sh -c #(nop) ADD file:b3ebbe8bd304723d4…   204MB

CMD和ENTRYPOINT区别展示

CMD

[root@localhost docker-test-v]# vim mydf-cmd-test
FROM centos
CMD ["ls","-a"]
[root@localhost docker-test-v]# docker build -f mydf-cmd-test -t centos-cmd-test .
Sending build context to Docker daemon  4.096kB
Step 1/2 : FROM centos
 ---> 5d0da3dc9764
Step 2/2 : CMD ["ls","-a"]
 ---> Running in 2b875583c5b5
Removing intermediate container 2b875583c5b5
 ---> fa2601e5666e
Successfully built fa2601e5666e
Successfully tagged centos-cmd-test:latest
[root@localhost docker-test-v]# docker run fa2601e5666e
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@localhost docker-test-v]# docker run fa2601e5666e -l
docker: Error response from daemon: OCI runtime create failed: runc create failed: unable to start container process: exec: "-l": executable file not found in $PATH: unknown.
ERRO[0000] error waiting for container: context canceled 

ENTRYPOINT

[root@localhost docker-test-v]# vim mydf-entry-test
FROM centos
ENTRYPOINT ["ls","-a"]
[root@localhost docker-test-v]# docker build -f mydf-entry-test -t centos-entry-test .
Sending build context to Docker daemon   5.12kB
Step 1/2 : FROM centos
 ---> 5d0da3dc9764
Step 2/2 : ENTRYPOINT ["ls","-a"]
 ---> Running in 1adc0700047e
Removing intermediate container 1adc0700047e
 ---> 784d65e0819a
Successfully built 784d65e0819a
Successfully tagged centos-entry-test:latest
[root@localhost docker-test-v]# docker run 784d65e0819a
.
..
.dockerenv
bin
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@localhost docker-test-v]# docker run 784d65e0819a -l
total 0
drwxr-xr-x.   1 root root   6 Aug 11 06:27 .
drwxr-xr-x.   1 root root   6 Aug 11 06:27 ..
-rwxr-xr-x.   1 root root   0 Aug 11 06:27 .dockerenv
lrwxrwxrwx.   1 root root   7 Nov  3  2020 bin -> usr/bin
drwxr-xr-x.   5 root root 340 Aug 11 06:27 dev
drwxr-xr-x.   1 root root  66 Aug 11 06:27 etc
drwxr-xr-x.   2 root root   6 Nov  3  2020 home
lrwxrwxrwx.   1 root root   7 Nov  3  2020 lib -> usr/lib
lrwxrwxrwx.   1 root root   9 Nov  3  2020 lib64 -> usr/lib64
drwx------.   2 root root   6 Sep 15  2021 lost+found
drwxr-xr-x.   2 root root   6 Nov  3  2020 media
drwxr-xr-x.   2 root root   6 Nov  3  2020 mnt
drwxr-xr-x.   2 root root   6 Nov  3  2020 opt
dr-xr-xr-x. 115 root root   0 Aug 11 06:27 proc
dr-xr-x---.   2 root root 162 Sep 15  2021 root
drwxr-xr-x.  11 root root 163 Sep 15  2021 run
lrwxrwxrwx.   1 root root   8 Nov  3  2020 sbin -> usr/sbin
drwxr-xr-x.   2 root root   6 Nov  3  2020 srv
dr-xr-xr-x.  13 root root   0 Aug 11 02:52 sys
drwxrwxrwt.   7 root root 171 Sep 15  2021 tmp
drwxr-xr-x.  12 root root 144 Sep 15  2021 usr
drwxr-xr-x.  20 root root 262 Sep 15  2021 var

制作Tomcat镜像

  1. 准备压缩包

    apache-tomcat-9.0.58.tar.gz jdk-8u211-linux-x64.tar.gz

  2. 准备dockerfile

    readme.txt 构建说明

    Dockerfile 官方命名 在build时就会自动去找这个命名 就不用-f 指定文件名了

    ADD 会自动解压缩

    FROM centos
    MAINTAINER wendy<zhiwen.ji@qq.com>
    
    COPY readme.txt /usr/local/readme.txt
    ADD apache-tomcat-9.0.58.tar.gz /usr/local/
    ADD jdk-8u211-linux-x64.tar.gz /usr/local/
    
    RUN yum -y install vim
    
    ENV MYPATH /usr/local/
    WORKDIR $MYPATH
    ENV JAVA_HOME /usr/local/jdk1.8.0_211/
    ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
    ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.58/
    ENV CATALINA_BASE /usr/local/apache-tomcat-9.0.58/
    ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/bin:$CATALINA_HOME/lib
    
    EXPOSE 8080
    CMD /usr/local/apache-tomcat-9.0.58/bin/startup.sh && tail -f /usr/local/apache-tomcat-9.0.58/logs/catalina.out
    
  3. 构建

    docker build -t diy-tomcat .

  4. 运行

    docker run --name diytomcat01 -d -p 9090:8080 -v /usr/local/docker-tomcat/test/:/usr/local/apache-tomcat-9.0.58/webapps/test/ -v /usr/local/docker-tomcat/logs/:/usr/local/apache-tomcat-9.0.58/logs/ diy-tomcat 
    
  5. 测试挂载

    本机可以看到logs目录下日志,并在test创建一个应用(只有html测试),访问可以看到就是成功了

    [root@localhost docker-tomcat]# ls
    apache-tomcat-9.0.58.tar.gz  Dockerfile  jdk-8u211-linux-x64.tar.gz  logs  readme.txt  test
    [root@localhost docker-tomcat]# ls logs/
    catalina.2022-08-11.log  host-manager.2022-08-11.log  localhost_access_log.2022-08-11.txt
    catalina.out             localhost.2022-08-11.log     manager.2022-08-11.log
    [root@localhost docker-tomcat]# ls test/
    index.html  WEB-INF
    

发布镜像

发布到DockerHub

先注册dockerhub账号,再登陆

dokcer login -u zhiwenj
password: ****

发布,作者/名称:版本号

docker push zhiwenj/diy-tomcat:1.0

报错:An image does not exist locally with the tag: wendy/diy-tomcat

因为本地是latest,没带版本号,所以需要重写定一个版本号

docker tag 330f41ec0790 zhiwenj/diy-tomcat:1.0

然后重新发布

发布到阿里云

注册 - 登陆 - 设置registry密码 - 创建命名空间 - 创建仓库 - 查看说明 - 推送

docker login --username=wenenenenen registry.cn-hangzhou.aliyuncs.com
docker tag [ImageId] registry.cn-hangzhou.aliyuncs.com/wendy-docker-test/test-01:[镜像版本号]
docker push registry.cn-hangzhou.aliyuncs.com/wendy-docker-test/test-01:[镜像版本号]

命令小结

If you haven’t already, read through the swarm mode overview and key concepts.

查看swarm命令

[root@localhost ~]# docker swarm --help
Usage:	docker swarm COMMAND
Manage Swarm
Commands:
  ca          Display and rotate the root CA
  init        Initialize a swarm
  join        Join a swarm as a node and/or manager
  join-token  Manage join tokens
  leave       Leave the swarm
  unlock      Unlock swarm
  unlock-key  Manage the unlock key
  update      Update the swarm
Run 'docker swarm COMMAND --help' for more information on a command.

流程:首先初始化(init)一台机器成为manager节点,并暴露(--advertise-addr)自己的地址,让其他节点加入join进来选择成为manager或者是worker

# 初始化一个manager 当前机器docker-1 ip为192.168.137.4
[root@localhost ~]# docker swarm init --advertise-addr 192.168.137.4
Swarm initialized: current node (slclpnonzlpn8lse1of09e6zl) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4euindy8toduoh3va8vyqz7xdjn6rkgn3p77g4tiomif6f27bx-06l4erft7xek04ytewiega313 192.168.137.4:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.


#  生成worker join的token
[root@localhost ~]# docker swarm join-token worker
To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4euindy8toduoh3va8vyqz7xdjn6rkgn3p77g4tiomif6f27bx-06l4erft7xek04ytewiega313 192.168.137.4:2377
#  生成manager join的token
[root@localhost ~]# docker swarm join-token manager
To add a manager to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4euindy8toduoh3va8vyqz7xdjn6rkgn3p77g4tiomif6f27bx-bahthzqdkjntmde2ghl0mw0jk 192.168.137.4:2377


# 加入docker-1集群 成为一个worker 当前机器docker-2 ip为192.168.137.5
# 报错 Error response from daemon: rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = "transport: Error while dialing dial tcp 192.168.137.4:2377: connect: no route to host"
# 需要关闭防火墙或者打开端口  否则端口docker-1的2377端口联不通
# 关闭防火墙  
# systemctl stop firewalld 
# 开放端口  
# firewall-cmd --zone=public --add-port=2377/tcp --permanent
# firewall-cmd --reload
[root@localhost ~]# docker swarm join --token SWMTKN-1-4euindy8toduoh3va8vyqz7xdjn6rkgn3p77g4tiomif6f27bx-06l4erft7xek04ytewiega313 192.168.137.4:2377
This node joined a swarm as a worker.

# 加入docker-1集群 成为一个worker 当前机器docker-3 ip为192.168.137.6
[root@localhost ~]# docker swarm join --token SWMTKN-1-4euindy8toduoh3va8vyqz7xdjn6rkgn3p77g4tiomif6f27bx-06l4erft7xek04ytewiega313 192.168.137.4:2377
This node joined a swarm as a worker.

# 加入docker-1集群 成为一个manager 当前机器docker-4 ip为192.168.137.7
# 报错 Error response from daemon: manager stopped: can't initialize raft node: rpc error: code = Unknown desc = could not connect to prospective new cluster member using its advertised address: rpc error: code = Unavailable desc = all SubConns are in TransientF
# 成为manager就需要关闭防火墙或者打开端口  只打开docker-1的不行 这个也需要打开 方式同上
[root@bogon ~]# docker swarm join --token SWMTKN-1-4euindy8toduoh3va8vyqz7xdjn6rkgn3p77g4tiomif6f27bx-bahthzqdkjntmde2ghl0mw0jk 192.168.137.4:2377
This node joined a swarm as a manager.

#  最终在docker-1 查看节点
[root@localhost ~]# docker node ls
ID                            HOSTNAME                STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
3cy2vkwbe2kuefw3goqa3mcow     localhost               Ready               Active              Reachable           19.03.12
ijsh1hquejkzghwxz7al17jiu     localhost.localdomain   Ready               Active                                  19.03.12
rtigefxbfuql7o3dh53px14yn *   localhost.localdomain   Ready               Active              Leader              19.03.12
xgwd0fwqmjdo27hte2yye3p6o     localhost.localdomain   Ready               Active                                  19.03.12

Raft协议

双主双从: 假设一个主节点挂了,另一个主节点也不可用!!

Raft一致性协议:理解:就是保证绝大多数节点是存货的才可用,就是高可用理念,双主双从挂一个的剩一个的话,还谈什么高可用。所以集群的数量最起码大于三台。 两主只要挂一个就都不可用,三主挂一个另外两个还可用,挂两个就都不可用了。高可用就是 > 1。

测试:双主双从挂一个,另一个也不可用

# docker-1 docker-4 是主  docker-2 docker-3 是从
[root@localhost ~]# docker node ls
ID                            HOSTNAME                STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
3cy2vkwbe2kuefw3goqa3mcow     localhost               Ready               Active              Reachable           19.03.12
ijsh1hquejkzghwxz7al17jiu     localhost.localdomain   Ready               Active                                  19.03.12
rtigefxbfuql7o3dh53px14yn *   localhost.localdomain   Ready               Active              Leader              19.03.12
xgwd0fwqmjdo27hte2yye3p6o     localhost.localdomain   Ready               Active                                  19.03.12
# 关闭 docker-1
[root@localhost ~]# systemctl stop docker
# docker-4 查看节点
[root@localhost ~]# docker node ls
Error response from daemon: rpc error: code = DeadlineExceeded desc = context deadline exceeded
# 开启 docker-1
[root@localhost ~]# systemctl start docker
# docker-1 或者 docker-4查看节点  发现docker-4成了Leader
[root@localhost ~]# docker node ls
ID                            HOSTNAME                STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
3cy2vkwbe2kuefw3goqa3mcow *   localhost               Ready               Active              Leader              19.03.12
rtigefxbfuql7o3dh53px14yn     localhost               Ready               Active              Reachable           19.03.12
xgwd0fwqmjdo27hte2yye3p6o     localhost               Ready               Active                                  19.03.12
ijsh1hquejkzghwxz7al17jiu     localhost.localdomain   Ready               Active                                  19.03.12

测试:三主一从挂一个,另外两个可用,挂两个都不可用

# 先把一个worker docker-3离开再添加成为manager 
# docker-3
[root@localhost ~]# docker swarm leave
Node left the swarm.
[root@localhost ~]# docker swarm join --token SWMTKN-1-24ysfnawimd0who3788enz230baj1grsb0gubouwsvm8njun77-ep7bmlbflhv8yeyd2nnmxdl5s 192.168.137.4:2377
This node joined a swarm as a manager.
[root@localhost ~]# docker node ls
ID                            HOSTNAME                STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
3cy2vkwbe2kuefw3goqa3mcow     localhost               Ready               Active              Leader              19.03.12
rtigefxbfuql7o3dh53px14yn     localhost               Ready               Active              Reachable           19.03.12
xgwd0fwqmjdo27hte2yye3p6o     localhost               Ready               Active                                  19.03.12
64b53pz8t50l46jv5wt5cs7of     localhost.localdomain   Down                Active                                  19.03.12
cmfh7kn7ojmoxlxbg5w5ptf35 *   localhost.localdomain   Ready               Active              Reachable           19.03.12
ijsh1hquejkzghwxz7al17jiu     localhost.localdomain   Down                Active                                  19.03.12
# 停掉 docker-1
[root@localhost ~]# systemctl stop docker
# docker-3 查看
[root@localhost ~]# docker node ls
ID                            HOSTNAME                STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
3cy2vkwbe2kuefw3goqa3mcow     localhost               Ready               Active              Leader              19.03.12
rtigefxbfuql7o3dh53px14yn     localhost               Down                Active              Unreachable         19.03.12
xgwd0fwqmjdo27hte2yye3p6o     localhost               Ready               Active                                  19.03.12
64b53pz8t50l46jv5wt5cs7of     localhost.localdomain   Down                Active                                  19.03.12
cmfh7kn7ojmoxlxbg5w5ptf35 *   localhost.localdomain   Ready               Active              Reachable           19.03.12
ijsh1hquejkzghwxz7al17jiu     localhost.localdomain   Down                Active                                  19.03.12
# docker-4查看
[root@localhost ~]# docker node ls
ID                            HOSTNAME                STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
3cy2vkwbe2kuefw3goqa3mcow *   localhost               Ready               Active              Leader              19.03.12
rtigefxbfuql7o3dh53px14yn     localhost               Down                Active              Unreachable         19.03.12
xgwd0fwqmjdo27hte2yye3p6o     localhost               Ready               Active                                  19.03.12
64b53pz8t50l46jv5wt5cs7of     localhost.localdomain   Down                Active                                  19.03.12
cmfh7kn7ojmoxlxbg5w5ptf35     localhost.localdomain   Ready               Active              Reachable           19.03.12
ijsh1hquejkzghwxz7al17jiu     localhost.localdomain   Down                Active                                  19.03.12

# 再停掉docker-4
[root@localhost ~]# systemctl stop docker
# docker-3查看
[root@localhost ~]# docker node ls
Error response from daemon: rpc error: code = DeadlineExceeded desc = context deadline exceeded

动态扩缩容

nginx搭建为例

企业级使用docker时,基本告别使用docker run 命令,docker-compose up 也是单机部署使用的,在swarm里,使用命令为docker service

概念变化:启动容器 -> 启动服务 -> 启动副本

redis集群就是一个redis服务,有10个副本就是开启了10个容器,动态扩缩容就是动态的增减副本。类似灰度发布,金丝雀发布的概念

# 当前 三主一从 docker-2从 docker-1 3 4 主
[root@docker-1 /]# docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
rtigefxbfuql7o3dh53px14yn *   docker-1            Ready               Active              Leader              19.03.12
xgwd0fwqmjdo27hte2yye3p6o     docker-2            Ready               Active                                  19.03.12
cmfh7kn7ojmoxlxbg5w5ptf35     docker-3            Ready               Active              Reachable           19.03.12
3cy2vkwbe2kuefw3goqa3mcow     docker-4            Ready               Active              Reachable           19.03.12
[root@docker-1 /]# docker service --help
Usage:	docker service COMMAND
Manage services
Commands:
  create      Create a new service
  inspect     Display detailed information on one or more services
  logs        Fetch the logs of a service or task
  ls          List services
  ps          List the tasks of one or more services
  rm          Remove one or more services
  rollback    Revert changes to a service's configuration
  scale       Scale one or multiple replicated services
  update      Update a service
Run 'docker service COMMAND --help' for more information on a command.
# 创建一个服务 可想象为docker run 命令,不过是创建成了swarm集群
[root@docker-1 /]# docker service create -p 8888:80 --name my-nginx nginx
3hh8ny611f3kms7hhutn1xzdd
overall progress: 1 out of 1 tasks 
1/1: running   
verify: Service converged 

#  查看服务  详细:docker service inspect my-nginx
[root@docker-1 /]# docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
3hh8ny611f3k        my-nginx            replicated          1/1                 nginx:latest        *:8888->80/tcp
[root@docker-1 /]# docker service ps my-nginx
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
l702uvr4ogf7        my-nginx.1          nginx:latest        docker-4            Running             Running 3 minutes ago    
# 现在可以在docker-1 2 3 4 上docker ps找一下看刚才启动的nginx服务  其本身的副本  也就是容器是跑在哪里的  发现是在docker-4里面
[root@docker-4 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
69985d9e1116        nginx:latest        "/docker-entrypoint.…"   8 minutes ago       Up 8 minutes        80/tcp              my-nginx.1.l702uvr4ogf7ewdeynbz4xgng

docker run 容器单机启动,不具有扩缩容功能

dokcer service 容器服务启动,可以动态扩缩容,滚动更新

访问: 容器虽然运行docker-4里面 ,但是访问三台主机任意一个都是可以访问成功的 http://192.168.137.4:8888/

# 那么意思就是默认情况下 create出来的服务  就只有一个副本  也就是只会创建一个容器  如果现在访问量增大  一个容器顶不住  需要增加集群数量  这个时候就需要用到扩缩容了

# 更新服务的副本数为3 那么现在docker ps会发现docker-1 3 4 都出现了nginx
[root@docker-1 /]# docker service update --replicas 3 my-nginx
my-nginx
overall progress: 3 out of 3 tasks 
1/3: running   
2/3: running   
3/3: running   
verify: Service converged 
# 副本数量是不受服务器数量限制的 只要服务器硬件条件足够就行  目前有docker-1 2 3 4 四台虚拟机 要更新服务为10个副本也是可以的 就是每台虚拟机上多跑几个容器 就是docker容器的特性  一个镜像可以运行多个容器
#  这时docker ps就发现docker-1运行了2个nginx容器 docker-2运行了3个 docker-3运行了2个  docker-4运行了3个
[root@docker-1 /]# docker service update --replicas 10 my-nginx
my-nginx
overall progress: 10 out of 10 tasks 
1/10: running   
2/10: running   
3/10: running   
4/10: running   
5/10: running   
6/10: running   
7/10: running   
8/10: running   
9/10: running   
10/10: running   
verify: Service converged 
#  如果流量变小了  不需要这么多副本了  也可以动态更新更少的副本
# 这时docker ps发现只有docker-4上有运行的1个容器了
[root@docker-1 /]# docker service update --replicas 1 my-nginx
my-nginx
overall progress: 1 out of 1 tasks 
1/1: running   
verify: Service converged 

另一个扩缩容命令 docker service scale 服务名=副本数

# 效果等同于 update命令
[root@docker-4 ~]# docker service scale my-nginx=3
my-nginx scaled to 3
overall progress: 3 out of 3 tasks 
1/3: running   
2/3: running   
3/3: running   
verify: Service converged 
[root@docker-4 ~]# docker service scale my-nginx=2
my-nginx scaled to 2
overall progress: 2 out of 2 tasks 
1/2: running   
2/2: running   
verify: Service converged 
# 移除服务命令
[root@docker-4 ~]# docker service rm my-nginx
my-nginx

让服务只在工作节点上运行,需要再创建时加上参数--mode

# --help 说明 
# --mode string  Service mode (replicated or global) (default "replicated")
# replicated: 指定几个副本 就会创建几个容器 初始化就是一个副本 只会创建一个容器
# global: 全局都有  初始化在四台虚拟机上都有一个容器
docker service create --mode replicated --name mytom tomcat:9 默认的
docker service create --mode global --name mytom tomcat:9

概念总结

swarm

集群的管理和编号,docker可以初始化一个swarm集群,其他节点可以加入,有管理节点manager和工作节点worker

node

就是一个docker集群节点,多个节点就组成了一个网络集群

service

任务,可以在管理节点或者工作节点来运行,是swarm核心

task

容器内的命令,细节任务,容器的创建与维护

拓展:swarm网络模式

docker service inspect my-nginx 发现网路模式是:"PublishMode":"ingress"

ingress 是特殊的Overlay网路,有负载均衡功能,虽然docker在4台机器上,但实际上网络是同一个。

以下有用到以后再学↓

方式:先找案例跑起来,再研究命令

Docker Stack

docker-compose 单机部署项目

docker stack 集群部署项目

[root@docker-1 /]# docker stack --help

Usage:	docker stack [OPTIONS] COMMAND

Manage Docker stacks

Options:
      --orchestrator string   Orchestrator to use
                              (swarm|kubernetes|all)

Commands:
  deploy      Deploy a new stack or update an existing stack
  ls          List stacks
  ps          List the tasks in the stack
  rm          Remove one or more stacks
  services    List the services in the stack

Run 'docker stack COMMAND --help' for more information on a command.

Docker Secret

安全相关

[root@docker-1 /]# docker secret --help

Usage:	docker secret COMMAND

Manage Docker secrets

Commands:
  create      Create a secret from a file or STDIN as content
  inspect     Display detailed information on one or more secrets
  ls          List secrets
  rm          Remove one or more secrets

Run 'docker secret COMMAND --help' for more information on a command.

Docker Config

配置相关

[root@docker-1 /]# docker config --help

Usage:	docker config COMMAND

Manage Docker configs

Commands:
  create      Create a config from a file or STDIN
  inspect     Display detailed information on one or more configs
  ls          List configs
  rm          Remove one or more configs

Run 'docker config COMMAND --help' for more information on a command.

热门相关:我家老公超宠哒   欧神   林家有女异世归   末日终战   重生娘子在种田