简介

提供一个标准化的解决方案:系统平滑移植,容器虚拟化技术

虚拟机属于虚拟化技术,docker容器技术也是一种虚拟化技术,相对于虚拟机,更加轻便。

docker基于go语言开发

官网:

Docker: Accelerated Container Application Development

官方文档:

Docker Documentation

社区:

Docker Hub Container Image Library | App Containerization

虚拟机使用缺点

  1. 资源占用多
  2. 步骤繁琐
  3. 启动慢

容器化

  1. 容器并不是一个完整的操作系统
  2. 容器直接运行在宿主机的内核,容器没有自己的内核(与宿主机共享内核),没有虚拟硬件(传统虚拟机会虚拟出一套硬件,运行一个完整的操作系统)
  3. 每个容器间是互相隔离的
  4. 每个容器有自己的文件系统

优点:

  1. 应用更快速的交付和部署
    1. 打包镜像,发布,一键运行
  2. 更便捷的扩容、缩容
  3. 更简单的系统运维
    1. 开发、测试环境高度一致
  4. 更高效的资源利用

安装/卸载

centos7

# 系统内核版本
uname -r

# 查看系统信息
cat /etc/os-release
  • 删除之前的版本
sudo yum remove docker \\
                  docker-client \\
                  docker-client-latest \\
                  docker-common \\
                  docker-latest \\
                  docker-latest-logrotate \\
                  docker-logrotate \\
                  docker-engine
  • 安装yum-utils
sudo yum install -y yum-utils
  • 设置docker仓库国内镜像源

**http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo**

yum-config-manager \\
    --add-repo \\
    **<http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo**>
  • yum更新索引
yum makecache
  • 安装 Docker Engine

    docker-ce 社区版

    docker-ee 企业版

sudo yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin
  • 启动docker
sudo systemctl start docker
docker version

 

  • 测试hello-world
sudo docker run hello-world
  • 卸载docker

# 卸载依赖
sudo yum remove docker-ce docker-ce-cli containerd.io

# 删除目录  /var/lib/docker 为docker的默认工作路径
sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd

使用

  • 查看镜像

    [root@VM-8-5-centos tommy]# docker images
    REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
    hello-world   latest    feb5d9fea6a5   7 months ago   13.3kB
    
  • 配置镜像加速器

    vim /etc/docker/daemon.json
    
    # 添加内容
    {
       "registry-mirrors": [
           "<https://mirror.ccs.tencentyun.com>"
      ]
    }
    
    # 重启docker
    sudo systemctl daemon-reload
    sudo systemctl restart docker
    
  • 运行流程

        

  • 原理

    Docker是一个client-server结构的系统,Docker的守护进程运行在主机上。客户端和服务端之间通过socket连接。(类似mysql)

  • Docker为什么比虚拟机快

        

  • Docker有着比虚拟机更少的抽象层。

    Docker利用的是宿主机的内核,而虚拟机需要初始化Guest OS。

    Docker不需要进行虚拟硬件的初始化,只需有一个Docker engine,即可初始化多个容器。

    新建一个容器的时候,Docker不需要重新加载一个操作系统,而虚拟机需要。

  • 常用命令

    # 帮助命令
    docker 命令 --help
    # 版本信息
    docker version
    # 详细信息
    docker info
    
  • 镜像命令

    # 镜像列表
    docker images
    
    # -a 显示所有
    # -q 只显示id
    
    
    # 搜索镜像
    docker search
    
    [root@VM-8-5-centos /]# docker search mysql
    NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    mysql                            MySQL is a widely used, open-source relation…   12484     [OK]       
    mariadb                          MariaDB Server is a high performing open sou…   4808      [OK]       
    mysql/mysql-server               Optimized MySQL Server Docker images. Create…   925                  [OK]
    percona                          Percona Server is a fork of the MySQL relati…   575       [OK]       
    phpmyadmin                       phpMyAdmin - A web interface for MySQL and M…   517       [OK]       
    mysql/mysql-cluster              Experimental MySQL Cluster Docker images. Cr…   93                   
    bitnami/mysql                    Bitnami MySQL Docker Image                      70                   [OK]
    ubuntu/mysql                     MySQL open source fast, stable, multi-thread…   31                   
    circleci/mysql                   MySQL is a widely used, open-source relation…   25                   
    mysql/mysql-router               MySQL Router provides transparent routing be…   23                   
    google/mysql                     MySQL server for Google Compute Engine          21                   [OK]
    
    # 条件搜索 STARS > 9000
    docker search mysql -f=STARS=9000
    
    # 下载镜像
    [root@VM-8-5-centos ~]# docker pull openjdk:8
    8: Pulling from library/openjdk
    # 分层下载
    6aefca2dc61d: Pull complete  
    967757d56527: Pull complete 
    c357e2c68cb3: Pull complete 
    c766e27afb21: Pull complete 
    a747e81e6111: Pull complete 
    10af0cb495fd: Pull complete 
    e8694e9cc467: Pull complete 
    # 签名
    Digest: sha256:bda4739c44b15f4a6ef4aa044e032809dd0ced24263c972bb728a0388275548b
    Status: Downloaded newer image for openjdk:8
    # 真实地址
    docker.io/library/openjdk:8
    # 等价于
    docker pull docker.io/library/openjdk:8
    
    
    # 删除镜像 -f 强制删除
    docker rmi -f
    # 删除多个容器
    docker rmi -f 容器id 容器id 容器id ...
    # 删除所有镜像 
    docker rmi -f $(docker images -qa)
    
  • 容器命令

    有了镜像才可以创建容器

    # 拉取容器
    docker pull 
    # 测试 拉取一个centos镜像
    docker pull centos 
    
    # 启动容器
    docker run [可选参数] image(镜像名)
    
    --name="Name"  容器名 mysql01 mysql02
    -d  后台方式运行
    -it 使用交互方式启动容器,可进入容器查看内容
    -p  指定容器端口 3306:3306
    	-p 主机端口:容器端口 和主机端口映射 
    	-p 容器端口
    	容器端口(简写方式,省略-p)
    -P  随机指定端口
    
    # 测试,启动并进入容器
    docker run -d --name="test" centos /bin/bash 
    [root@VM-8-5-centos ~]# docker run -it centos /bin/bash
    [root@bf855d7a48e4 /]# ls # 查看容器内的centos目录
    bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    # 退出容器 并停止
    exit
    [root@bf855d7a48e4 /]# exit
    exit
    [root@VM-8-5-centos ~]#
    # 退出容器 不停止
    control + p + q
    
    

    docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会停止

  • docker ps

    # 查看容器运行状态 docker ps
    [root@VM-8-5-centos ~]# docker ps -a
    CONTAINER ID   IMAGE         COMMAND                  CREATED              STATUS                          PORTS     NAMES
    81403451a39f   centos        "/bin/bash"              2 seconds ago        Exited (0) 1 second ago                   centos02
    d8f703569143   centos        "/bin/bash"              About a minute ago   Exited (127) 59 seconds ago               centos01
    096e267260b5   centos        "/bin/bash --name=ce…"   About a minute ago   Exited (2) About a minute ago             gracious_elgamal
    4d6dc6ded48b   centos        "/bin/bash -name=cen…"   About a minute ago   Exited (1) About a minute ago             intelligent_torvalds
    ba8cc6ff9dd3   centos        "/bin/bash --name=ce…"   2 minutes ago        Exited (2) 2 minutes ago                  clever_davinci
    7bf580df146a   centos        "/bin/bash -name=cen…"   2 minutes ago        Exited (1) 2 minutes ago                  brave_goldstine
    55b8f88982e4   centos        "-name=centos1"          2 minutes ago        Created                                   sharp_cerf
    bf855d7a48e4   centos        "/bin/bash"              42 minutes ago       Exited (0) 35 minutes ago                 stupefied_burnell
    7896a5b5ed08   centos        "/bin/bash"              42 minutes ago       Exited (0) 42 minutes ago                 gallant_almeida
    2aa7de89ec6e   hello-world   "/hello"                 6 days ago           Exited (0) 6 days ago                     recursing_panini
    19449585e90c   hello-world   "/hello"                 6 days ago           Exited (0) 6 days ago                     peaceful_nobel
    
  • docker rm

    # 删除容器
    # 删除指定容器 不能删除正在运行的容器 
    docker rm 容器id
    # 删除所有容器
    docker rm -f $(docker ps -aq)
    
    
  • docker start/restart/stop

    # 启动
    docker start 容器id
    # 重启
    docker restart 容器id
    # 停止正在运行的容器
    docker stop 容器id
    # 强制停止
    docker kill 容器id
    
    
  • 查看日志

    # -f 格式化
    # -t 时间戳
    # --tail num 显示指定行数
    docker logs -f -t --tail xxx
    
    [root@VM-8-5-centos ~]# docker run -d --name="cenots01" centos /bin/bash -c "while true;do echo tommy;sleep 1;done"
    4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc
    [root@VM-8-5-centos ~]# docker ps
    CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
    4a38847371a7   centos    "/bin/bash -c 'while…"   8 seconds ago   Up 7 seconds             cenots01
    [root@VM-8-5-centos ~]# docker logs -tf --tail 10  4a38847371a7
    2022-05-13T02:31:39.607913293Z tommy
    2022-05-13T02:31:40.610043614Z tommy
    2022-05-13T02:31:41.612341621Z tommy
    2022-05-13T02:31:42.614418244Z tommy
    2022-05-13T02:31:43.616457222Z tommy
    
  • 容器中进程信息

    docker top 容器id
    
    [root@VM-8-5-centos ~]# docker top 4a38847371a7
    UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
    root                31509               31488               0                   10:38               ?                   00:00:00            /bin/bash -c while true;do echo tommy;sleep 1;done
    root                31565               31509               0                   10:38               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
    
  • 查看容器元数据

    docker inspect 容器id
    
    [root@VM-8-5-centos ~]# docker inspect 4a38847371a7
    [
        {
            "Id": "4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc",
            "Created": "2022-05-13T02:29:37.014454616Z",
            "Path": "/bin/bash",
            "Args": [
                "-c",
                "while true;do echo tommy;sleep 1;done"
            ],
            "State": {
                "Status": "running",
                "Running": true,
                "Paused": false,
                "Restarting": false,
                "OOMKilled": false,
                "Dead": false,
                "Pid": 31509,
                "ExitCode": 0,
                "Error": "",
                "StartedAt": "2022-05-13T02:38:07.725942472Z",
                "FinishedAt": "2022-05-13T02:32:38.091008451Z"
            },
            "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
            "ResolvConfPath": "/var/lib/docker/containers/4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc/resolv.conf",
            "HostnamePath": "/var/lib/docker/containers/4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc/hostname",
            "HostsPath": "/var/lib/docker/containers/4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc/hosts",
            "LogPath": "/var/lib/docker/containers/4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc/4a38847371a746c696d592e24d90d14a0a8021b995e0f82611e7f95dd2efb0dc-json.log",
            "Name": "/cenots01",
            "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/ce9251d3af5baa01e7c9592b73f005cd67ca33a401f79a3807cdf9dbcc1e1e30-init/diff:/var/lib/docker/overlay2/a75ed65e92dda7fa07ad103a8f02e236f650631c76b207044be48d19704fb5ad/diff",
                    "MergedDir": "/var/lib/docker/overlay2/ce9251d3af5baa01e7c9592b73f005cd67ca33a401f79a3807cdf9dbcc1e1e30/merged",
                    "UpperDir": "/var/lib/docker/overlay2/ce9251d3af5baa01e7c9592b73f005cd67ca33a401f79a3807cdf9dbcc1e1e30/diff",
                    "WorkDir": "/var/lib/docker/overlay2/ce9251d3af5baa01e7c9592b73f005cd67ca33a401f79a3807cdf9dbcc1e1e30/work"
                },
                "Name": "overlay2"
            },
            "Mounts": [],
            "Config": {
                "Hostname": "4a38847371a7",
                "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/bash",
                    "-c",
                    "while true;do echo tommy;sleep 1;done"
                ],
                "Image": "centos",
                "Volumes": null,
                "WorkingDir": "",
                "Entrypoint": null,
                "OnBuild": null,
                "Labels": {
                    "org.label-schema.build-date": "20210915",
                    "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": "bb5fe3acd88052302266383738d15c54694268db5c389397aaced1b812256909",
                "HairpinMode": false,
                "LinkLocalIPv6Address": "",
                "LinkLocalIPv6PrefixLen": 0,
                "Ports": {},
                "SandboxKey": "/var/run/docker/netns/bb5fe3acd880",
                "SecondaryIPAddresses": null,
                "SecondaryIPv6Addresses": null,
                "EndpointID": "1d2f536cdcbc0ab2388cf8ca7a2b69d33ee4503f563ffac9c04460761441b5bd",
                "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": "2534bfc35b4533fe5605b337be7804ea983c11aa60e6950175034068c4477cd5",
                        "EndpointID": "1d2f536cdcbc0ab2388cf8ca7a2b69d33ee4503f563ffac9c04460761441b5bd",
                        "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

    进入容器后开启一个新的终端

    # 通常容器都是使用后台方式运行的,如果需要进入正在运行的容器修改一些配置
    
    	docker exec -it 容器id bashShell
    
    [root@VM-8-5-centos ~]# docker exec -it 4a38847371a7 /bin/bash
    [root@4a38847371a7 /]# ls
    bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    [root@4a38847371a7 /]#
    

    docker attach

    进入容器正在执行的终端,不会启动新的进程

    docker attach 容器id
    
    [root@VM-8-5-centos ~]# docker attach 4a38847371a7
    tommy
    tommy
    tommy
    tommy
    
  • 从容器内拷贝文件到主机上

    docker cp 容器id:容器内路径 目的主机路径
    
    # 将容器4a38847371a7内/home下的tommy.txt文件拷贝到主机的/tommy目录下
    docker cp 4a38847371a7:/home/tommy.txt /tommy
    

 

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部