Docker

Docker

Docker安装

环境查看

# 系统内核 3.10 以上
[root@localhost ~]# uname -r
3.10.0-123.el7.x86_64
# 系统版
[root@localhost ~]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

安装

查看帮助文档

# 1.卸载旧版本
yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
已加载插件:fastestmirror, langpacks
参数 docker 没有匹配
参数 docker-client 没有匹配
参数 docker-client-latest 没有匹配
参数 docker-common 没有匹配
参数 docker-latest 没有匹配
参数 docker-latest-logrotate 没有匹配
参数 docker-logrotate 没有匹配
参数 docker-engine 没有匹配
不删除任何软件包
​
# 2.需要的安装包
yum install -y yum-utils
​
# 3.设置镜像仓库
yum-config-manager \
    --add-repo \
    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
​
# 更新yum软件包索引
yum makecache fast
​
# 4.安装docker相关内容 docker-ce 社区版本 ee 企业版
yum install docker-ce docker-ce-cli containerd.io 
​
# 5.启动docker
systemctl start docker
​
# 6.测试hello-world
docker run hello-world

 

镜像操作

帮助命令

docker version
docker info
docker 命令 --help    #帮助命令

命令地址

Reference documentation | Docker Documentation

 

镜像命令

docker images | Docker Documentation

docker images 查看所有本地的主机上的镜像

[root@iZwz9abebnlkcgilriwvczZ ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    d1165f221234   2 months ago   13.3kB
​
# 解释
REPOSITORY  镜像的仓库源
TAG 镜像的标签
IMAGE ID    镜像的ID
CREATED 镜像的创建时间
SIZE    镜像大小
​
# 可选项
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests    # 显示镜像的摘要信息
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output   # 显示完整的镜像信息
  -q, --quiet           Only show image IDs # 只显示镜像id
​
[root@iZwz9abebnlkcgilriwvczZ /]# docker images --digests
REPOSITORY   TAG       DIGEST                                                                    IMAGE ID       CREATED        SIZE
centos       latest    sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1   300e315adb2f   5 months ago   209MB
​
[root@iZwz9abebnlkcgilriwvczZ /]# docker images --no-trunc
REPOSITORY   TAG       IMAGE ID                                                                  CREATED        SIZE
centos       latest    sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55   5 months ago   209MB
​
[root@iZwz9abebnlkcgilriwvczZ /]# docker ps 
CONTAINER ID   IMAGE     COMMAND       CREATED              STATUS              PORTS     NAMES
42f226eb1c0d   centos    "/bin/bash"   About a minute ago   Up About a minute             vibrant_goodall
[root@iZwz9abebnlkcgilriwvczZ /]# docker images -q
300e315adb2f

docker search 搜索镜像

[root@iZwz9abebnlkcgilriwvczZ ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10877     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4103      [OK]       
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   808                  [OK]
percona                           Percona Server is a fork of the MySQL relati…   537       [OK]       
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   87                   
mysql/mysql-cluster               Experimental MySQL Cluster Docker images. Cr…   83                   
centurylink/mysql                 Image containing mysql. Optimized to be link…   59                   [OK]
bitnami/mysql                     Bitnami MySQL Docker Image                      52                   [OK]
databack/mysql-backup             Back up mysql databases to... anywhere!         43                   
​
# 可选项
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output
​
--filter=STARS=3000 # 搜索出来的镜像的STARS大于3000
[root@iZwz9abebnlkcgilriwvczZ ~]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   10877     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4103      [OK]   

docker pull 下载镜像

# 下载镜像 docker pull 镜像名[:tag]
​
[root@iZwz9abebnlkcgilriwvczZ ~]# docker pull nginx
Using default tag: latest   # 没有tag默认下载最新的版本
latest: Pulling from library/nginx
69692152171a: Pull complete     # 分层下载 docker image的核心 联合文件系统
49f7d34d62c1: Pull complete 
5f97dc5d71ab: Pull complete 
cfcd0711b93a: Pull complete 
be6172d7651b: Pull complete 
de9813870342: Pull complete 
Digest: sha256:df13abe416e37eb3db4722840dd479b00ba193ac6606e7902331dcea50f4f1f2 # 签名
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest  # 真实地址
​
# 等价
docker pull nginx
docker pull docker.io/library/nginx:latest
​
# 指定版本下载
[root@iZwz9abebnlkcgilriwvczZ ~]# docker pull nginx:1.20.0
1.20.0: Pulling from library/nginx
69692152171a: Already exists 
965615a5cec8: Pull complete 
b141b026b9ce: Pull complete 
8d70dc384fb3: Pull complete 
525e372d6dee: Pull complete 
6e60219fdb98: Pull complete 
Digest: sha256:ea4560b87ff03479670d15df426f7d02e30cb6340dcd3004cdfc048d6a1d54b4
Status: Downloaded newer image for nginx:1.20.0
docker.io/library/nginx:1.20.0

docker rmi 删除镜像

# 删除指定ID的镜像
[root@iZwz9abebnlkcgilriwvczZ ~]# docker rmi -f d1165f221234
Untagged: hello-world:latest
Untagged: hello-world@sha256:5122f6204b6a3596e048758cabba3c46b1c937a46b5be6225b835d091b90e46c
Deleted: sha256:d1165f2212346b2bab48cb01c1e39ee8ad1be46b87873d9ca7a4e434980a7726
 
# 循环删所有的镜像 
[root@iZwz9abebnlkcgilriwvczZ ~]# docker rmi -f $(docker images -aq)
Untagged: nginx:1.20.0
Untagged: nginx@sha256:ea4560b87ff03479670d15df426f7d02e30cb6340dcd3004cdfc048d6a1d54b4
Deleted: sha256:7ab27dbbfbdf4031f0603a4b597cc43031ff883b54f9329f0309c80952dda6f5
Deleted: sha256:5b2a9404d052ae4205f6139190fd4b0921ddeff17bf2aaf4ee97f79e1a8242fe
Deleted: sha256:03ebf76f0cbf5fd32ca010bb589c2139ce7e44c050fe3de2d77addf4cfd25866
Deleted: sha256:0191669d087dce47072254a93fe55cbedd687f27d3798e2260f846e8f8f5729a
Deleted: sha256:17651c6a0ba04d31da14ac6a86d8fb3f600883f9e155558e8aad0b94aa6540a2
Deleted: sha256:5a673ff4c07a1b606f2ad1fc53697c99c45b0675734ca945e3bb2bd80f43feb8
Untagged: nginx:latest
Untagged: nginx@sha256:df13abe416e37eb3db4722840dd479b00ba193ac6606e7902331dcea50f4f1f2
Deleted: sha256:f0b8a9a541369db503ff3b9d4fa6de561b300f7363920c2bff4577c6c24c5cf6
Deleted: sha256:60f61ee7da08c2a5c5f6a76c1f2926f50ba1d01d8ec4af9afb8fdcd3d97ef6f9
Deleted: sha256:affa58c5a9d1d907c11d8589d4e08d2dc8e4e6b71b141269405a2e67d0a8b011
Deleted: sha256:6b1533d42f38a9c55cad97d4e01c03756ab82b61798b6c4f4bc9122093bb6ebd
Deleted: sha256:5c3e94c8305f2a4158258725fe33d2451842c13a97c76f02042a7a7e0aa3799a
Deleted: sha256:adda6567aeaa86913f56f0e4647032e1d9347bd63ed98a320f904c71df2637c1
Deleted: sha256:02c055ef67f5904019f43a41ea5f099996d8e7633749b6e606c400526b2c4b33

容器命令

docker pull centos

新建容器并启动

docker run [可选参数] image

# 参数说明
--name="Name"	容器命名 tomcat01 tomcat02 用来区分容器
-d	后台方式运行
-it	使用交互方式运行,进入容器查看内容
-p	指定容器的端口 -p 8080:8080
	-p ip:主机端口:容器端口
	-p 主机端口:容器端口
	-p 容器端口
	容器端口
-P	随机指定端口

## 测试	启动并进入容器
[root@iZwz9abebnlkcgilriwvczZ ~]# docker run -it centos /bin/bash
[root@eb294ec26294 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

列出所有运行的容器

# docker ps 命令	列出当前正在运行的容器
	-a # 列出当前正在运行的容器+历史运行过的容器
	-n=? #	显示最近创建的容器
	-q # 只显示容器的编号

[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED         STATUS                     PORTS     NAMES
eb294ec26294   centos         "/bin/bash"   3 minutes ago   Exited (0) 2 minutes ago             goofy_rubin
a9f2bc5d3d11   d1165f221234   "/hello"      24 hours ago    Exited (0) 24 hours ago              modest_brattain

[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps -a -n=1
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
eb294ec26294   centos    "/bin/bash"   5 minutes ago   Exited (0) 5 minutes ago             goofy_rubin

[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps -aq
eb294ec26294
a9f2bc5d3d11

# docker ps -l 列出最近创建的容器
[root@iZwz9abebnlkcgilriwvczZ /]# docker ps -l
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
42f226eb1c0d   centos    "/bin/bash"   7 minutes ago   Up 7 minutes             vibrant_goodall

# docker ps -n 3   列出最近创建的3个容器
[root@iZwz9abebnlkcgilriwvczZ /]# docker ps -n 3
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                      PORTS     NAMES
42f226eb1c0d   centos    "/bin/bash"   8 minutes ago    Up 8 minutes                          vibrant_goodall
c014ab0bfe53   centos    "/bin/bash"   23 minutes ago   Exited (0) 21 minutes ago             nervous_boyd

# docker ps -q	只显示容器ID
[root@iZwz9abebnlkcgilriwvczZ /]# docker ps -q
42f226eb1c0d

# docker ps --no-trunc	显示当前所有正在运行的容器完整信息
[root@iZwz9abebnlkcgilriwvczZ /]# docker ps --no-trunc
CONTAINER ID                                                       IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
42f226eb1c0d6386117497aa937840b017b751b4cfa5189c5e536eb60e9b6068   centos    "/bin/bash"   10 minutes ago   Up 10 minutes             vibrant_goodall

退出容器

exit	# 直接停止容器并退出
Ctrl + p + q #容器不停止退出

删除容器

docker rm 容器ID	# 删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -f
docker rm -f $(docker ps -aq)	# 删除所有的容器
docker ps -a -q|xargs docker rm # 删除所有的容器

启动和停止容器

docker start 容器ID	# 启动容器
docker restart 容器ID	# 重启容器
docker stop 容器ID	# 停止当前正在运行的容器
docker kill	容器ID	# 强制停止当前正在运行的容器

常用的其他容器命令

后台启动

# 命令 docker run -d 镜像名称
[root@iZwz9abebnlkcgilriwvczZ ~]# docker run -d centos
ecb89d0e48e9c8550b523602167af0dfc1eea0669dc0ff276dff404d70b82368
[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps 
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# docker ps 发现centos停止了

# 常见的坑,docker 容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
# Nginx 容器启动后,发现自己没有提供服务,就会立即停止,就没有程序了

# docker run -it --rm tomcat:9.0

查看日志

docker logs -f -t --since --tail 容器ID或容器名称查看容器日志
如:docker logs -f -t --since=”2018-09-10” --tail=10 f9e29e8455a5
 -f : 查看实时日志
 -t : 查看日志产生的日期
 --since : 此参数指定了输出日志开始日期,即只输出指定日期之后的日志
 --tail=10 : 查看最后的10条日志

# docker logs -tf --tail 10 容器

# 自己写shell脚本
[root@iZwz9abebnlkcgilriwvczZ ~]# docker run -d centos /bin/sh -c "while true;do echo aaaa;sleep 1;done"
a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6

[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
a4fd6e22b342   centos    "/bin/sh -c 'while t…"   4 seconds ago   Up 3 seconds             inspiring_taussig

# 查看日志
	-tf	# 显示日志
	--tail number # 显示日志条数
[root@iZwz9abebnlkcgilriwvczZ ~]# docker logs -tf --tail 10 a4fd6e22b342
2021-05-17T23:07:25.588638428Z aaaa
2021-05-17T23:07:26.590396195Z aaaa
2021-05-17T23:07:27.592193662Z aaaa
2021-05-17T23:07:28.594091709Z aaaa
2021-05-17T23:07:29.596074529Z aaaa
2021-05-17T23:07:30.597887342Z aaaa

查看容器中的进程信息

# 命令 docker top 容器ID
[root@iZwz9abebnlkcgilriwvczZ ~]# docker top a4fd6e22b342
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                13128               13091               0                   07:07               ?                   00:00:00            /bin/sh -c while true;do echo aaaa;sleep 1;done
root                17768               13128               0                   07:10               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

查看镜像元数据

# docker inspect 容器id
[root@iZwz9abebnlkcgilriwvczZ ~]# docker inspect --help

Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type

[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
a4fd6e22b342   centos    "/bin/sh -c 'while t…"   8 minutes ago   Up 8 minutes             inspiring_taussig
[root@iZwz9abebnlkcgilriwvczZ ~]# docker inspect a4fd6e22b342
[
    {
        "Id": "a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6",
        "Created": "2021-05-17T23:07:06.151189995Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo aaaa;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 13128,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-05-17T23:07:06.557297685Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
        "ResolvConfPath": "/var/lib/docker/containers/a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6/hostname",
        "HostsPath": "/var/lib/docker/containers/a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6/hosts",
        "LogPath": "/var/lib/docker/containers/a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6/a4fd6e22b3427e77296252e93793276baecac3f12da54db4c2fb05b4de271ef6-json.log",
        "Name": "/inspiring_taussig",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "host",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/bdd7c7cd42caa56b6168a39b82e2454e56b12bb4f2890215d047b9d1910f1ffe-init/diff:/var/lib/docker/overlay2/c7dd6c723fe2efafb06ca2a720d9bd92645ddf22e9b62ab5322f34bd7ae65d4a/diff",
                "MergedDir": "/var/lib/docker/overlay2/bdd7c7cd42caa56b6168a39b82e2454e56b12bb4f2890215d047b9d1910f1ffe/merged",
                "UpperDir": "/var/lib/docker/overlay2/bdd7c7cd42caa56b6168a39b82e2454e56b12bb4f2890215d047b9d1910f1ffe/diff",
                "WorkDir": "/var/lib/docker/overlay2/bdd7c7cd42caa56b6168a39b82e2454e56b12bb4f2890215d047b9d1910f1ffe/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "a4fd6e22b342",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true;do echo aaaa;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20201204",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "ef82935cb9d0074411b877f9de834a864ec7b7846fa68fb17626e453b602933b",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/ef82935cb9d0",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "f447164f738c290f5dce677d6a9baa78df61b5ee0303a20da658c5b91d78aa1a",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "aedf8c0e77694bc3b4e835ce58ad0e3f637b3eb716408c7bdc044bb578f459b1",
                    "EndpointID": "f447164f738c290f5dce677d6a9baa78df61b5ee0303a20da658c5b91d78aa1a",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

进入当前运行的容器

 # 命令
 docker exec -it 容器ID /bin/sh
# 测试
[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
a4fd6e22b342   centos    "/bin/sh -c 'while t…"   10 minutes ago   Up 10 minutes             inspiring_taussig
[root@iZwz9abebnlkcgilriwvczZ ~]# docker exec -it a4fd6e22b342 /bin/sh
sh-4.4# 

# 方式二
docker attach 容器ID

# 测试
[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
a4fd6e22b342   centos    "/bin/sh -c 'while t…"   13 minutes ago   Up 13 minutes             inspiring_taussig
[root@iZwz9abebnlkcgilriwvczZ ~]# docker attach a4fd6e22b342
aaaa
aaaa
aaaa
aaaa
aaaa

# docker exec 	# 进入容器并开启一个新的终端,可以在里面进行操作
# docker attach	# 进入容器正在执行的终端,不会启动新进程

从容器内拷贝文件到主机上

# docker cp 容器ID:容器内部路径 目的主机路径
[root@iZwz9abebnlkcgilriwvczZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED              STATUS              PORTS     NAMES
c014ab0bfe53   centos    "/bin/bash"   About a minute ago   Up About a minute             nervous_boyd
# 进入docker容器
[root@iZwz9abebnlkcgilriwvczZ ~]# docker attach c014ab0bfe53
[root@c014ab0bfe53 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@c014ab0bfe53 /]# cd home/
[root@c014ab0bfe53 home]# ls
# 创建文件
[root@c014ab0bfe53 home]# touch test.java
[root@c014ab0bfe53 home]# ls
test.java
[root@c014ab0bfe53 home]# exit
exit
[root@iZwz9abebnlkcgilriwvczZ ~]# cd /home/
[root@iZwz9abebnlkcgilriwvczZ home]# ls
# 拷贝文件
[root@iZwz9abebnlkcgilriwvczZ home]# docker cp c014ab0bfe53:/home/test.java /home
[root@iZwz9abebnlkcgilriwvczZ home]# ls
test.java

参考资料

https://www.docker.org.cn/

attach      Attach local standard input, output, and error streams to a running container
#当前shell下 attach连接指定运行的镜像
build       Build an image from a Dockerfile # 通过Dockerfile定制镜像
commit      Create a new image from a container's changes #提交当前容器为新的镜像
cp          Copy files/folders between a container and the local filesystem #拷贝文件
create      Create a new container #创建一个新的容器
diff        Inspect changes to files or directories on a container's filesystem #查看docker容器的变化
events      Get real time events from the server # 从服务获取容器实时时间
exec        Run a command in a running container # 在运行中的容器上运行命令
export      Export a container's filesystem as a tar archive #导出容器文件系统作为一个tar归档文件[对应import]
history     Show the history of an image # 展示一个镜像形成历史
images      List images #列出系统当前的镜像
import      Import the contents from a tarball to create a filesystem image #从tar包中导入内容创建一个文件系统镜像
info        Display system-wide information # 显示全系统信息
inspect     Return low-level information on Docker objects #查看容器详细信息
kill        Kill one or more running containers # kill指定docker容器
load        Load an image from a tar archive or STDIN #从一个tar包或标准输入中加载一个镜像[对应save]
login       Log in to a Docker registry #
logout      Log out from a Docker registry
logs        Fetch the logs of a container
pause       Pause all processes within one or more containers
port        List port mappings or a specific mapping for the container
ps          List containers
pull        Pull an image or a repository from a registry
push        Push an image or a repository to a registry
rename      Rename a container
restart     Restart one or more containers
rm          Remove one or more containers
rmi         Remove one or more images
run         Run a command in a new container
save        Save one or more images to a tar archive (streamed to STDOUT by default)
search      Search the Docker Hub for images
start       Start one or more stopped containers
stats       Display a live stream of container(s) resource usage statistics
stop        Stop one or more running containers
tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top         Display the running processes of a container
unpause     Unpause all processes within one or more containers
update      Update configuration of one or more containers
version     Show the Docker version information
wait        Block until one or more containers stop, then print their exit codes

实战

部署Nginx

# 下载镜像
[root@192 home]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
8559a31e96f4: Pull complete 
8d69e59170f7: Pull complete 
3f9f1ec1d262: Pull complete 
d1f5ff4f210d: Pull complete 
1e22bfa8652e: Pull complete 
Digest: sha256:21f32f6c08406306d822a0e6e8b7dc81f53f336570e852e25fbe1e3e3d0d0133
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

# 查看镜像
[root@192 home]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              831691599b88        13 hours ago        215MB
nginx               latest              2622e6cca7eb        7 days ago          132MB

# 运行测试
# -d 后台运行,--name 命名,-p 暴露端口,3344服务器、宿主机的端口:容器内部端口
[root@192 home]# docker run -d --name nginx01 -p 3344:80 nginx
38dbf7bdcaef232d269b7184d91e44e06087181b5ee929494e177ad526810fa8
[root@192 home]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
38dbf7bdcaef        nginx               "/docker-entrypoint.…"   7 seconds ago       Up 6 seconds        0.0.0.0:3344->80/tcp   nginx01

# 使用3344可以访问成功
[root@192 home]# curl localhost:3344
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

可视化工具

Portainer

commit镜像

docker commit -m="提交的描述信息" -a="作者" 容器id 目标镜像名,[TAG]

容器数据卷

docker是要将应用和环境打包成一个镜像,这样,数据就不应该在容器中,否则容器删除,数据就会丢失,这就是删库跑路;

故容器之间要有一个数据共享技术,在Docker容器中产生的数据,同步到本地,这就是卷技术。

本质上是一个目录挂载,将容器内的目录挂载到虚拟机上

目的:容器的持久化和同步操作,容器间可以数据共享

使用数据卷

方式一:直接使用命令来挂载

docker run -it -v 本机目录:容器目录 -p
# -it 交互式进入
# -v volume卷技术
# -p 主机端口

# 例
docker run -it -v /home/demo:/home centos /bin/bash 

image-20200618163659503

新开一个窗口

docker inspect 容器id

image-20200618163938466

找到挂载信息Mounts

image-20200618164148642

测试

image-20200618164818624

容器停止后,修改主机文件,再启动容器的时候,数据同样改变

具名和匿名挂载

DockerFile

构建步骤

  1. 编写一个dockerfile文件

  2. docker build 构建成为一个镜像

  3. docker run运行镜像

  4. docker push 发布镜像(DockerHub、阿里云镜像仓库 私有/共有)

DockerFile基础知识

  1. 每个指令都必须是大写字母

  2. 按照从上到下顺序执行

  3. #表示注释

  4. 每一个指令都会创建体检一个新的镜像层,并提交

image-20200621174948310

DockerFile命令

FROM # 基础镜像 比如centos
MAINTAINER # 镜像是谁写的 姓名+邮箱
RUN # 镜像构建时需要运行的命令
ADD # 添加,比如添加一个tomcat压缩包
WORKDIR # 镜像的工作目录
VOLUME # 挂载的目录
EXPOSE # 指定暴露端口,跟-p一个道理
RUN # 最终要运行的
CMD # 指定这个容器启动的时候要运行的命令,只有最后一个会生效,而且可被替代
ENTRYPOINT # 指定这个容器启动的时候要运行的命令,可以追加命令
ONBUILD # 当构建一个被继承Dockerfile 这个时候运行ONBUILD指定,触发指令
COPY # 将文件拷贝到镜像中
ENV # 构建的时候设置环境变量

官方的DockerFile

image-20200621174204807

实战构建自己的centos

添加centos7的压缩包

# 创建一个自己的centos
# 进入home目录
cd /home

# 创建一个目录,之后的东西都保存到这里
mkdir dockerfile
# 进入这个目录
cd dockerfile/
# 创建一个dockerfile,名字叫mydockerfile
vim mydockerfile-centos
#下面给官方centos加上自定义的内容
FROM centos
MAINTAINER padaxing<010301200@hai.com>

ENV MYPATH /usr/local
WORKDIR $MYPATH

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

EXPOSE 80

CMD echo $MYPATH
CMD echo "---end---"
CMD /bin/bash

下面通过这个这个文件创建镜像

docker build -f dockerfile-centos -t mycentos:0.1

image-20200621190219978

启动镜像

docker run -it mycentos:0.1 # 版本号必须写,不然他会去找最新的
pwd
vim
ifconfig

image-20200621190812481

可以通过查看docker构建历史

image-20200621192103460

CMD与ENTRYPOINT

FROM centos
CMD ["ls","-a"] # 启动centos展示目录

image-20200622075427103

image-20200622075653789

实战Tomcat镜像

1.准备镜像文件 tomcat压缩包,jdk压缩包

image-20210416091759250

2.编写Dockerfile文件,官方命名“Dockerfile”, build会自动寻找这个文件,就不需要 -f 指定了

FROM centos
   
MAINTAINER kun<529295745@qq.com>
   
COPY readme.txt  /usr/local/readme.txt  
   
ADD jdk-8u281-linux-x64.tar.gz    /usr/local/
ADD apache-tomcat-8.5.59.tar.gz /usr/local/
   
RUN yum -y install vim
ENV MYPATH /usr/local
   
WORKDIR $MYPATH
   
ENV JAVA_HOME /usr/local/jdk1.8.0_281
   
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
   
ENV CATALINA_HOME /usr/local/apache-tomcat-8.5.59
ENV CATALINA_BASH /usr/local/apache-tomcat-8.5.59
   
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
EXPOSE 8080
CMD /usr/local/apache-tomcat-8.5.59/bin/startup.sh && tail -F /usr/local/apache-tomcat-8.5.59/bin/logs/catalina.out

image-20210416095729416

3.使用build命令编译 ,由于命名为 "Dockerfile" 可以不加 -f 命令

# 1.构建镜像
docker build -t diytomcat .
   
# 2.挂载目录
docker run -d -p 9090:8080 --name ptomcat -v /home/tomcat/test:/usr/local/apache-tomcat-8.5.59/webapps/test -v /home/tomcat/build/tomcat/tomcatlogs/:/usr/local/apache-tomcat-8.5.59/logs diytomcat

4.启动镜像,访问测试

docker exec -it 2c0a0fe71f7c /bin/bash

Docker网络

查看本机的 ip addr

[root@kk ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:c1:13:6d brd ff:ff:ff:ff:ff:ff
    inet 192.168.204.130/24 brd 192.168.204.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::62dc:f8a3:a777:e321/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
    link/ether 52:54:00:c3:d5:6c brd ff:ff:ff:ff:ff:ff
    inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
       valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 state DOWN group default qlen 1000
    link/ether 52:54:00:c3:d5:6c brd ff:ff:ff:ff:ff:ff
  
# 给 docker分配了一个ip
5: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:00:eb:57:0d brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:ff:feeb:570d/64 scope link 
       valid_lft forever preferred_lft forever

启动tomcat,并查看容器内部的 ip addr

# 1.下载tomcat  以后台的方式进行运行
docker run -d -it -P --name tomcat01 tomcat

#2. 进入tomcat 容器 执行 ip addr 命令       eth0@if27 此地址为 docker自动生成
[root@kk ~]# docker exec  -it tomcat01 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
26: eth0@if27: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
       
 #3. 测试ip地址能否通信   ping 172.17.0.2
[root@kk ~]# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.048 ms

在主机中再次 ip addr 发现 多了一个 网卡

[root@kk ~]# ip addr
5: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:00:eb:57:0d brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:ff:feeb:570d/64 scope link 
       valid_lft forever preferred_lft forever
 # 此处即是  启动容器后  产生的新的网卡
27: veth8a743b7@if26: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether 02:9f:47:48:82:cc brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet6 fe80::9f:47ff:fe48:82cc/64 scope link 
       valid_lft forever preferred_lft forever
  
 # 再次启动第二个tomcat容器后,又多了一对网卡 
29: veth56293aa@if28: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether 36:ec:01:06:de:d7 brd ff:ff:ff:ff:ff:ff link-netnsid 1
    inet6 fe80::34ec:1ff:fe06:ded7/64 scope link 
       valid_lft forever preferred_lft forever

测试两个容器之间的通信

[root@kk ~]# docker exec tomcat02 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
28: eth0@if29: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
[root@kk ~]# docker exec tomcat01 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
26: eth0@if27: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
# 两个容器之间可以完美通信
[root@kk ~]# docker exec tomcat02 ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.170 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.074 ms

原理

  • 我们发现这个容器带来网卡,都是"一对对的"

  • veth-pair就是一对的虚拟设备接口,他们都是成对出现的

  • 一段连着协议,一段彼此相连正因为有这个特性,veth-pair充当一个桥梁,连接各种虚拟网络设备的

image-20210416175057521

小结

tomcat01和 tomcat02是公用的一个路由器, docker0所有的容器不指定网络的情况下,都是 docker0路由的, docker会给我们的容器分配一个默认的可用

image-20210416192102726

link

思考一个场景,我们编写了一个微服务, database url:=ip:,项目不重启,数据库ip换掉了,我们希望可以处理这个问题,可以名字来进行访问容器?

# 1.直接用容器名称ping  不通
[root@kk ~]# docker exec -it tomcat01 ping tomcat02
ping: tomcat02: Name or service not known

#2. 用  --link  命令启动    单向可以ping 通
[root@kk ~]# docker run -d -it -P --name tomcat03 --link tomcat01 tomcat
02978b9e75c3d8c094ecc8cb74cb32ed4fbf92ef2f6eb53331eff5677c2a47ab
[root@kk ~]#  docker exec -it tomcat01 ping tomcat03
ping: tomcat03: Name or service not known
[root@kk ~]#  docker exec -it tomcat03 ping tomcat01
PING tomcat01 (172.17.0.2) 56(84) bytes of data.
64 bytes from tomcat01 (172.17.0.2): icmp_seq=1 ttl=64 time=0.325 ms
64 bytes from tomcat01 (172.17.0.2): icmp_seq=2 ttl=64 time=0.085 ms

单向联通的原因

[root@kk ~]#  docker exec -it tomcat03 cat /etc/hosts
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
172.17.0.2	tomcat01 2b05ac88444c #  tomcat03 中直接指明了  tomcat01 的ip
172.17.0.4	02978b9e75c3
[root@kk ~]#  docker exec -it tomcat01 cat /etc/hosts
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
172.17.0.2	2b05ac88444c   #  tomcat01 中没有 tomcat03的地址

本质探究

link就是我们在 tomcat03 的 hosts配置中增加了一个172.17.0.2 tomcat01 2b05ac88444c

我们现在玩 Docker已经不建议使用link

自定义网络连接

网络模式

  • bridge:桥接 docker(默认,自己创建也使用 bridge模式)

  • none:不配置网络

  • host:和宿主机共享网络

  • container:容器网络连通!(用的少!局限很大)

    #我们可以自定义一个网络
    # --driver bridge	
    #-- subnet192.168.0.0/16
    #-- gateway192.168.0.1
    [root@kk ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
    21501df4c37c77fcbb0c61b3bdd776ede7a29802c8234413bbb85e525722a087
    [root@kk ~]# docker network ls
    NETWORK ID     NAME      DRIVER    SCOPE
    275762873e27   bridge    bridge    local
    9293b8c12edf    host      host      local
    21501df4c37c   mynet     bridge    local
    dca3d5c20357   none      null      local
    
    # 查看自定义网络的信息
    [root@kk ~]# docker network inspect mynet
    [
        {
            "Name": "mynet",
            "Id": "21501df4c37c77fcbb0c61b3bdd776ede7a29802c8234413bbb85e525722a087",
            "Created": "2021-04-16T20:30:22.78506401+08:00",
            "Scope": "local",
            "Driver": "bridge",
            "EnableIPv6": false,
            "IPAM": {
                "Driver": "default",
                "Options": {},
                "Config": [
                    {
                        "Subnet": "192.168.0.0/16",
                        "Gateway": "192.168.0.1"
                    }
                ]
            },
            "Internal": false,
            "Attachable": false,
            "Ingress": false,
            "ConfigFrom": {
                "Network": ""
            },
            "ConfigOnly": false,
            "Containers": {},
            "Options": {},
            "Labels": {}
        }
    ]

在自定义的网络里启动两个tomcat

[root@kk ~]# docker run -d -P --name tomcat-net-01 --net mynet tomcat
6f693e658afec4ac39c6c7f762c0bfa5be5da2bfe1730b7a8ae059e441edb1d5
[root@kk ~]# docker run -d -P --name tomcat-net-02 --net mynet tomcat
38934ce91b2b6ddf51ae3933b7733818ce4319620cf520d88c262ed403b49459

# 查看自定义的网络,发现里面多了两个容器的信息
[root@kk ~]# docker network inspect mynet
[
   ...
        "Containers": {
            "38934ce91b2b6ddf51ae3933b7733818ce4319620cf520d88c262ed403b49459": {
                "Name": "tomcat-net-02",
                "EndpointID": "2a1baa06127e83037dfbc53523f7a749b3246026489de88a1c566739c7a315eb",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            },
            "......: {
                "Name": "tomcat-net-01",
                "EndpointID": "........",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            },
       ...
]

# 两个容器之间相互用 名称 ping
[root@kk ~]# docker exec tomcat-net-01 ping tomcat-net-02
PING tomcat-net-02 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.073 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.066 ms

[root@kk ~]# docker exec tomcat-net-02 ping tomcat-net-01
PING tomcat-net-01 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.055 ms
64 bytes from tomcat-net-01.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.078 ms

网络之间的联通

# 1.在默认的 dockers0 下开启一个 tomcat
[root@kk ~]# docker run -d -P --name tomcat01 tomcat
4d46cb8b8200848e6ba095d7d0fb76a73470653b72efbbf7a480fce6c4070d8b

#2.测试  该 docker0 下的 tomcat 与 mynet 下的 tomcat-net-02  之间的通信   无法联通
[root@kk ~]# docker exec tomcat01 ping tomcat-net-02
ping: tomcat-net-02: Name or service not known

[root@kk ~]# docker network connect --help
Usage:  docker network connect [OPTIONS] NETWORK CONTAINER

Connect a container to a network

Options:
      --alias strings           Add network-scoped alias for the container
      --driver-opt strings      driver options for the network
      --ip string               IPv4 address (e.g., 172.30.100.104)
      --ip6 string              IPv6 address (e.g., 2001:db8::33)
      --link list               Add link to another container
      --link-local-ip strings   Add a link-local address for the container
   
 #3.使用  docker network connect   将容器和网络联通
[root@kk ~]# docker network connect mynet tomcat01
[root@kk ~]# docker network inspect mynet
[
 		...
        "Containers": {
            "38934ce91b2b6ddf51ae3933b7733818ce4319620cf520d88c262ed403b49459": {
                "Name": "tomcat-net-02",
                "EndpointID": "2a1baa06127e83037dfbc53523f7a749b3246026489de88a1c566739c7a315eb",
                "MacAddress": "02:42:c0:a8:00:03",
                "IPv4Address": "192.168.0.3/16",
                "IPv6Address": ""
            },
   #4. 发现此处多了一个 容器    即   tomcat01 有两个地址,一个在网络  docker0   一个就是 mynet
            "4d46cb8b8200848e6ba095d7d0fb76a73470653b72efbbf7a480fce6c4070d8b": {
                "Name": "tomcat01",
                "EndpointID": "39f637c20175499052aa4474ba9022de1bf23ffe2a86fbcdd5155ac5f3f7309a",
                "MacAddress": "02:42:c0:a8:00:04",
                "IPv4Address": "192.168.0.4/16",
                "IPv6Address": ""
            },
            "6f693e658afec4ac39c6c7f762c0bfa5be5da2bfe1730b7a8ae059e441edb1d5": {
                "Name": "tomcat-net-01",
                "EndpointID": "ecc240f9051d0d64ee773eba961761e739cd31d4d83e1f6a4d04df4f712c75d8",
                "MacAddress": "02:42:c0:a8:00:02",
                "IPv4Address": "192.168.0.2/16",
                "IPv6Address": ""
            }
    ...
]
# 5.再次测试 两者之间的联通情况   成功ping通,相互均可访问
[root@kk ~]# docker exec tomcat01 ping tomcat-net-02
PING tomcat-net-02 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.148 ms
64 bytes from tomcat-net-02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.066 ms

[root@kk ~]# docker exec tomcat-net-01 ping tomcat01
PING tomcat01 (192.168.0.4) 56(84) bytes of data.
64 bytes from tomcat01.mynet (192.168.0.4): icmp_seq=1 ttl=64 time=0.076 ms
64 bytes from tomcat01.mynet (192.168.0.4): icmp_seq=2 ttl=64 time=0.080 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值