02-Docker

作者: 紫荆秋雪_文 | 来源:发表于2021-10-11 15:48 被阅读0次

一、Docker架构

Docker架构.png

Docker服务中各个角色

  • Client:客户端,操作Docker服务器的客户端(命令行 或 界面)
  • DOCKER_HOST:Docker主机,安装Docker服务的主机
  • Docker_Daemon:后台进程,运行在Docker服务器的后台进程
  • Containers:容器,在Docker服务器中容器(一个容器一般是一个应用实例,容器间相互隔离)
  • Images:镜像、映射、程序包,Image是只读模板,其中包含创建Docker容器的说明。容器是由Image运行而来,Image固定不变
  • Registries:仓库,存储Docker Image的地方。官方远程仓库

二、Docker隔离原理

namespace 6项隔离(资源隔离) image.png

cgroups资源限制(资源限制)

  • 资源限制:限制任务使用的资源总额,并在超过这个 配额 时发出提示
  • 优先级分配:分配 CPU 时间片数量及磁盘IO贷款大小、控制任务运行的优先级
  • 资源统计:统计系统资源使用量,如 CPU 使用时长、内存用量
  • 任务控制:对任务执行挂起、恢复等操作


    image.png

三、Docker安装

1、移除旧版本

sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

2、设置 docker yum源

sudo yum install -y yum-utils

sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

3、安装最新docker engine

sudo yum install docker-ce docker-ce-cli containerd.io

4、查看docker版本

yum list docker-ce --showduplicates | sort -r

5、安装指定版本docker

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

eg:
sudo yum install docker-ce-3:19.03.9-3.el7.x86_64 docker-ce-cli-3:19.03.9-3.el7.x86_64 containerd.io

6、启动docker

sudo systemctl start docker

7、设置开机启动

sudo systemctl enable docker

8、设置镜像加速(阿里云)

  • 登录阿里云,搜索 镜像服务
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://knk5i905.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

四、docker命令

命令 作用
attach 绑定到运行中容器的标准输入、输出,以及错误流(这样似乎也能进入容器内容,但是一定小心,他们操作的就是控制台,控制台的退出命令会生效,比如:redis,Nginx)
build 从一个 Dockerfile 文件构建镜像
commit 把容器的改变提交创建一个新的镜像
cp 容器和宿主机文件系统 复制文件 / 文件夹
create 创建新容器,但并不启动(与docker run 的区别)需要手动启动。start / stop
diff 检测容器里文件系统结构的更改。(A:添加文件或目录;D:删除文件或者目录;C:更改文件或者目录)
events 获取服务器的实时事件
exec 进入正在运行的容器内部命令
export 导出容器的文件系统为一个 tar 文件。commit是直接提交成为一个镜像,export是导出成文件方便传输
history 显示镜像的历史
images 列出所有镜像
import 导入 tar 的内容创建一个镜像,再导入进来的镜像直接启动不了容器。需要使用 /docker-entrypoint.sh nginx -g 'daemon ow;' 启动。docker ps --no-trunc 看下之前的完整启动命令再用他
info 显示系统信息
inspect 获取 docker 对象的底层信息
kill 杀死一个或者多个容器
load 从 tar 文件加载镜像
login 登录 Docker Registry
logout 退出 Docker Registry
logs 获取容器日志;容器以前在前台控制台能输出的所有内容,都可以看到
pause 暂停一个或者多个容器
port 列出容器的端口映射
ps 列出容器的端口映射
pull 从 Registry 下载一个 Image 或者 Repository
push 给 Registry 推送一个 Image 或者 Repository
rename 重命名一个容器
restart 重启一个或者多个容器
rm 移除一个或者多个容器
rmi 移除一个或者多个镜像
run 创建并启动容器
save 把一个或者多个镜像保存为 tar 文件
search 去 Docker Hub 寻找镜像
start 启动一个或者多个容器
stats 显示容器资源的实时使用状态
stop 停止一个或者多个容器
tag 给源镜像创建一个新的标签,变成新的镜像
top 显示正在运行容器的进程
unpause pause的反操作
update 更新一个或者多个 docker 容器配置
version 显示 docker 版本信息
container 管理容器
image 管理镜像
network 管理网络
volume 管理券
  • 删除全部容器
docker rm -f $(docker ps -aq)

五、Docker 实操

Docker Hub

image.png

镜像是什么?

  • 镜像就是基础环境 + 软件
  • Nginx镜像:linux系统 + Nginx软件
  • alpine:超级经典版linux,特别小,推荐下载带有alpine的镜像

5-1、镜像相关操作命令

1、查看当前镜像

docker images
docker images.png

2、搜索镜像,或从 DockerHub搜索

docker search nginx
image.png

3、拉取镜像

docker pull nginx
image.png
  • 再次查询当前镜像,Nginx 镜像已经拉取下来 image.png

4、查看镜像历史-history

image.png

5.1、删除镜像-rmi

image.png

5.2、删除全部镜像

docker rmi -f $(docker images -aq) #删除全部镜像

6、重新命名镜像-tag

docker tag 原镜像:标签 新镜像名:标签 #重命名
docker tag nginx:latest nginx:v1
image.png

5-2、容器相关操作命令

1.1、创建前台容器

docker run --name mynginx -p 80:80 nginx
  • 前台启动容器会造成界面“卡死”,退出界面时,容器也会销毁,所以不推荐使用前台方式创建容器
  • 创建容器时一定要暴露端口,否则无法访问
  • 暴露端口时,: 前的端口时宿主机的端口,:后的端口时容器的端口


    image.png

1.2、创建后台容器

docker create --name mynginx -p 80:80 nginx:latest
docker run -d --name mynginx -p 80:80 nginx:latest
  • 主要
docker run -d = docker create + docker start
image.png
  • 此时容器已经创建,但是并没有启动,所以需要手动启动
docker start 19f9872bd2f862bfeb7c202913616d2b081f47cff37ff375a2b4922d116b5184
  • 访问容器 image.png

2、查看当前容器

docker ps  # 查看存活的容器
docker ps -a  #查看所有容器
image.png

3.1、停止容器-优雅停机

docker stop 容器名称/容器ID

3.2、停止容器-强制停机

docker kill 容器名称/容器ID

4.1、进入容器

  • docker attach 绑定的是控制台,可能导致容器停止。不推荐使用
docker attach 容器名称/容器ID

4.2、进入容器

  • u:指定用户
  • privileged:root用户权限
docker exec -it -u 0:0 --privileged 8f /bin/bash

5-3、其他操作

1、查看指定容器信息

docker container inspect 容器名称/容器ID
[
    {
        "Id": "8f748061c8633a4cab4b88e93e784386d6340f154842946489708d6e690cae3a",
        "Created": "2021-10-11T05:42:14.366993454Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 14034,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-10-11T05:46:59.65645698Z",
            "FinishedAt": "2021-10-11T05:45:30.906537809Z"
        },
        "Image": "sha256:f8f4ffc8092c956ddd6a3a64814f36882798065799b8aedeebedf2855af3395b",
        "ResolvConfPath": "/var/lib/docker/containers/8f748061c8633a4cab4b88e93e784386d6340f154842946489708d6e690cae3a/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/8f748061c8633a4cab4b88e93e784386d6340f154842946489708d6e690cae3a/hostname",
        "HostsPath": "/var/lib/docker/containers/8f748061c8633a4cab4b88e93e784386d6340f154842946489708d6e690cae3a/hosts",
        "LogPath": "/var/lib/docker/containers/8f748061c8633a4cab4b88e93e784386d6340f154842946489708d6e690cae3a/8f748061c8633a4cab4b88e93e784386d6340f154842946489708d6e690cae3a-json.log",
        "Name": "/mynginx",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "80"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "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/53b355159525f0416f9ecbd26be9805a1ec3669e1cb8d6a808a1b29e7f31aafa-init/diff:/var/lib/docker/overlay2/a42a845eb3a8c4ebd267fdc2fbabd8715f7ccb79421a749209ee941800d3b476/diff:/var/lib/docker/overlay2/2639f8f3420a4be991cbeec99a7469878a7e2b4800e7e0c63c07c640b46cbe96/diff:/var/lib/docker/overlay2/987ba75856862bd5fd1475ba04d4392ee1f1f2de2db4aa5f1bbf2b846ea4522c/diff:/var/lib/docker/overlay2/80814a5662b4893ef088766cb184621638635ec3be0b443cc77ec01ad5d9957d/diff:/var/lib/docker/overlay2/d8bf757fa7d333a578c0df3f857593246b4d1207388deab1680ea21b5daf3a69/diff:/var/lib/docker/overlay2/d3db0eb5df44cae935c00e0e8e2b56e3bdd45aac6e0274474c45fda7775a8fe5/diff",
                "MergedDir": "/var/lib/docker/overlay2/53b355159525f0416f9ecbd26be9805a1ec3669e1cb8d6a808a1b29e7f31aafa/merged",
                "UpperDir": "/var/lib/docker/overlay2/53b355159525f0416f9ecbd26be9805a1ec3669e1cb8d6a808a1b29e7f31aafa/diff",
                "WorkDir": "/var/lib/docker/overlay2/53b355159525f0416f9ecbd26be9805a1ec3669e1cb8d6a808a1b29e7f31aafa/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "8f748061c863",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.3",
                "NJS_VERSION=0.6.2",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx:latest",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "f595a73dbfadf0b60039a281e44e80b02a7036f83b658d7c92bc942ba0628d5a",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "80"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/f595a73dbfad",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "703c83a6d08f6cd2b931ae6d6e2c4e060d77d56bc36bd96db51a7670c8bce3d7",
            "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": "438e2a0e3e17fbe139fbe50c1b9641aaa6bc5aad85029898aa938e3d349cf8c4",
                    "EndpointID": "703c83a6d08f6cd2b931ae6d6e2c4e060d77d56bc36bd96db51a7670c8bce3d7",
                    "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
                }
            }
        }
    }
]

2、查看指定镜像信息

docker inspect 镜像名称 / 镜像ID
[
    {
        "Id": "sha256:f8f4ffc8092c956ddd6a3a64814f36882798065799b8aedeebedf2855af3395b",
        "RepoTags": [
            "nginx:latest",
            "nginx:v1"
        ],
        "RepoDigests": [
            "nginx@sha256:06e4235e95299b1d6d595c5ef4c41a9b12641f6683136c18394b858967cd1506"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2021-09-28T08:26:07.57996119Z",
        "Container": "449a8a48a9f56c3616a0b58ce3fea705fa34293def3c95bc32b50b9bc52f3ff7",
        "ContainerConfig": {
            "Hostname": "449a8a48a9f5",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.3",
                "NJS_VERSION=0.6.2",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"nginx\" \"-g\" \"daemon off;\"]"
            ],
            "Image": "sha256:dce61176f89cfe1ba4ca3eb3c39097b455d90108498072a77ebaac245c5732cc",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "DockerVersion": "20.10.7",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.3",
                "NJS_VERSION=0.6.2",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "sha256:dce61176f89cfe1ba4ca3eb3c39097b455d90108498072a77ebaac245c5732cc",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 133283279,
        "VirtualSize": 133283279,
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/2639f8f3420a4be991cbeec99a7469878a7e2b4800e7e0c63c07c640b46cbe96/diff:/var/lib/docker/overlay2/987ba75856862bd5fd1475ba04d4392ee1f1f2de2db4aa5f1bbf2b846ea4522c/diff:/var/lib/docker/overlay2/80814a5662b4893ef088766cb184621638635ec3be0b443cc77ec01ad5d9957d/diff:/var/lib/docker/overlay2/d8bf757fa7d333a578c0df3f857593246b4d1207388deab1680ea21b5daf3a69/diff:/var/lib/docker/overlay2/d3db0eb5df44cae935c00e0e8e2b56e3bdd45aac6e0274474c45fda7775a8fe5/diff",
                "MergedDir": "/var/lib/docker/overlay2/a42a845eb3a8c4ebd267fdc2fbabd8715f7ccb79421a749209ee941800d3b476/merged",
                "UpperDir": "/var/lib/docker/overlay2/a42a845eb3a8c4ebd267fdc2fbabd8715f7ccb79421a749209ee941800d3b476/diff",
                "WorkDir": "/var/lib/docker/overlay2/a42a845eb3a8c4ebd267fdc2fbabd8715f7ccb79421a749209ee941800d3b476/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:476baebdfbf7a68c50e979971fcd47d799d1b194bcf1f03c1c979e9262bcd364",
                "sha256:5259501115588b1be0b1bb6eee115422d2939f402137979603cea9d9f1e649ec",
                "sha256:0772cb25d5cae1b4e6e47ff15af95fa1d2640c3b7c74cb4c008d61e2c8c28559",
                "sha256:6e109f6c2f99fdfa436dd66299d2ed87a18fee00b5f22fbd761dbacac27b76a6",
                "sha256:88891187bdd7d71eeaa5f468577eb253eca29f57e3577ea0a954f6991313fd71",
                "sha256:65e1ea1dc98ccb565bf8dd0f7664fc767796d3a6eecaf29b79ce7e9932517ae5"
            ]
        },
        "Metadata": {
            "LastTagTime": "2021-10-11T11:27:29.418812951+08:00"
        }
    }
]

3、使用当前容器制作镜像

8f748061c863:容器ID
docker commit -a Raven -m "测试 commit 命令" 8f748061c863 mynginx:v2
image.png

4、推送镜像到阿里云镜像仓库(没有账号需要提前注册号)

遇到Get https://registry.cn-hangzhou.aliyuncs.com/v2/: unauthorized: authentication required

解决方案:把--username=re****中*****用户名补全

操作指南-一定要将需要推送的镜像重命名后推送到指定仓库

阿里云镜像仓库.png

5、export 操作容器 / import

  • docker export 导出的文件被 import 导入以后变成镜像,并不能直接启动容器,需要知道之前的启动命令(docker ps --no-trunc),然后再用下面启动。或者 docker image inspect 看之前的镜像,把之前镜像的 Entrypoint 的所有和 Cmd 的连接起来就能得到启动命令
docker run -d -P mynginx:v6 /docker-entrypoint.sh nginx -g 'daemon off;'

6、save / load -- 操作镜像

docker save -o busybox.tar busybox:latest 把busybox镜像保存成tar文件 
docker load -i busybox.tar 把压缩包里面的内容直接导成镜像

六、docker run 参数说明

  • -d:后台运行容器,并返回容器ID
  • -i:以交换模式运行容器,通常与 -t 同时使用
  • -P:随机端口映射,容器内部端口随机映射到主机的端口
  • -p:指定端口映射,格式为主机(宿主机)端口:容器端口
  • -t:为容器重新分配一个伪输入终端,通常与-i同时使用
  • --name="nginx-lb":为容器指定一个名称
  • --dns 8.8.8.8:指定容器使用的 DNS 服务器,默认和宿主一致
  • --dns-search example.com:指定容器 DNS 搜索域名,默认和宿主一致
  • -h "mars":指定容器的 hostname
  • -e username="ritchie":设置环境变量
  • --env-file=[]:从指定文件读入环境变量
  • --cpuset="0.2" or --cpuset="0, 1, 2":绑定容器到指定 CPU 运行
  • -m:设置容器使用内存最大值
  • --net="bridge":指定容器的网络连接类型,支持 bridge / host / none / container 四种类型
  • --link=[]:开放一个端口或一组端口
  • --expose=[]:开放一个端口或一组端口
  • --restart:指定重启策略
  • --restart=awlays:总是故障重启
  • --volume,-v:绑定一个券。一般格式 宿主机文件或文件夹:虚拟机文件或文件夹

相关文章

网友评论

    本文标题:02-Docker

    本文链接:https://www.haomeiwen.com/subject/rcwholtx.html