Docker 学习

Posted _xk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Docker 学习相关的知识,希望对你有一定的参考价值。

先记录再整理

命令:

BASIS:

​ 如果项目都是自己处理过的镜像,例如用到了 mongodb, postgresql, php-fpm, nginx, 给这些镜像一个前缀或者后缀,例如 edu_ 或者_edu.

Example:

  • edu_mongo / mongo_edu
  • edu_postgres / postgres_edu
  • edu_php-fpm / php-fpm_edu
  • edu_nginx / nginx_edu

inspect:

​ 查看容器配置信息等

# 下面命令会输出一个 pretty json 里面都是 container 的信息
$ docker inspect <container name/container id>

​ 查看具体某一个配置

# key1 belong to value0 of key0 and key2 belong to value1 of key1 and so on
$ docker inspect -f=\'{{.<key0>[.<key1>][.key2][...]}}\' <container name/container id>
# or 
$ docker inspect --format=\'{{.<key0>[.<key1>][.key2][...]}}\' <container name/container id>
# example: 
#     docker inspect -f=\'{{.NetworkSettings}}\' nginx                   
# output: 
#     {{ 0f3f569dce91a16751c170f91ef9c8c128c757f86dff4e39f8ab58ae686f4edb false  0 map[80/tcp:[{0.0.0.0 9002} {:: 9002}]] /var/run/docker/netns/0f3f569dce91 [] []} {553e63fa029a7dc7e123c74b330830033fdcc2a409baae5745e3875d17d6d580 172.17.0.1  0 172.17.0.3 16  02:42:ac:11:00:03} map[bridge:0xc0003f0000]}

​ 格式化输出,上门的 -f 参数输出的数据格式,都是 value, 虽然排序是按顺序的,但是我们不知道 value 具体对应那个 key.

# 下面命令输出的是 json 格式的数据
$ docker inspect -f \'{{json .NetworkSettings.Networks}}\' nginx 
# 注意:
# 正确示例:
# docker inspect -f \'{{json .NetworkSettings.Networks}}\' nginx  -- √
# docker inspect -f=\'{{json .NetworkSettings.Networks}}\' nginx  -- √
# docker inspect --format=\'{{json .NetworkSettings.Networks}}\' nginx -- √ 
# docker inspect --format \'{{json .NetworkSettings.Networks}}\' nginx -- √ 
# 上面四个都是相等的,但是不要写成下面的
# 错误示例:
# docker inspect -f \'json {{.NetworkSettings.Networks}}\' nginx -- ×

# Output Example:         {"Bridge":"","SandboxID":"0f3f569dce91a16751c170f91ef9c8c128c757f86dff4e39f8ab58ae686f4edb","HairpinMode":false,"LinkLocalIPv6Address":"","LinkLocalIPv6PrefixLen":0,"Ports":{"80/tcp":[{"HostIp":"0.0.0.0","HostPort":"9002"},{"HostIp":"::","HostPort":"9002"}]},"SandboxKey":"/var/run/docker/netns/0f3f569dce91","SecondaryIPAddresses":null,"SecondaryIPv6Addresses":null,"EndpointID":"553e63fa029a7dc7e123c74b330830033fdcc2a409baae5745e3875d17d6d580","Gateway":"172.17.0.1","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"IPAddress":"172.17.0.3","IPPrefixLen":16,"IPv6Gateway":"","MacAddress":"02:42:ac:11:00:03","Networks":{"bridge":{"IPAMConfig":null,"Links":null,"Aliases":null,"NetworkID":"c8af3e9943e0555af10ad6436ec37906039780a897e6ed0c0eb1655c0847f65e","EndpointID":"553e63fa029a7dc7e123c74b330830033fdcc2a409baae5745e3875d17d6d580","Gateway":"172.17.0.1","IPAddress":"172.17.0.3","IPPrefixLen":16,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"MacAddress":"02:42:ac:11:00:03","DriverOpts":null}}}

​ 上面虽然输出了 JSON 格式, 但是挤在一起太乱了,要输出 pretty 的 JSON.

# 使用 jq 命令行格式化 json
$ docker inspect -f \'{{json .NetworkSettings.Networks}}\' nginx | jq
# or
$ docker inspect -f \'{{json .NetworkSettings.Networks}}\' nginx | python -m json.tool

注意:python 命令行工具可能显示 \'json\' is a package and cannot be directly executed,这样的话先执行下面命令。

$PS> python -c "import json"

Refs:

  • Docker格式化命令和日志输出
  • How do I check whether a module is installed in Python, and install it if needed?

stop(停止容器)

# 停止一个或者多个容器
PS> docker stop <container1_NameOrId> [<container2_NameOrId> ... <containerN_NameOrId>]

要批量停止这些带 edu_ 前缀或者 _edu 后缀的,需要通过匹配

# name:下面的例子,没有正则匹配,只要name 的内容匹配成功,都能显示出来
# Regular Express: 
#     只匹配开头 --filter="name=^edu"
#   只匹配结尾 --filter="name=edu$"
#   匹配开头或者结尾 --filter="name=^edu|edu$" // 用 | 分隔
# -q 是 只显示 container id 的意思
PS> docker stop $(docker container ls -q --filter="name=edu")
# or 
PS> docker stop $(docker ps -q --filter="name=edu")

start(启动容器)

# 启动一个或者多个容器
PS> docker start <container1_NameOrId> [<container2_NameOrId> ... <containerN_NameOrId>]

要批量启动这些带 edu_ 前缀或者 _edu 后缀的,需要通过匹配

# name:下面的例子,没有正则匹配,只要name 的内容匹配成功,都能显示出来
# Regular Express: 
#     只匹配开头 --filter="name=^edu"
#   只匹配结尾 --filter="name=edu$"
#   匹配开头或者结尾 --filter="name=^edu|edu$" // 用 | 分隔
# -q 是 只显示 container id 的意思
# 启动多个的时候,都要带上 -a, 因为无论是 docker container ls 还是 docker ps 默认都是显示已经启动的容器,所以需要带上 -a 表示显示全部容器
PS> docker start $(docker container ls -aq --filter="name=edu")
# or 
PS> docker start $(docker ps -aq --filter="name=edu")

rm(删除容器)

# 删除一个或者多个容器
PS> docker rm <container1_NameOrId> [<container2_NameOrId> ... <containerN_NameOrId>]

要批量删除这些带 edu_ 前缀或者 _edu 后缀的,需要通过匹配

# name:下面的例子,没有正则匹配,只要name 的内容匹配成功,都能显示出来
# Regular Express: 
#     只匹配开头 --filter="name=^edu"
#   只匹配结尾 --filter="name=edu$"
#   匹配开头或者结尾 --filter="name=^edu|edu$" // 用 | 分隔
# -q 是 只显示 container id 的意思
# 删除多个的时候,都要带上 -a, 因为无论是 docker container ls 还是 docker ps 默认都是显示已经启动的容器,所以需要带上 -a 表示显示全部容器
PS> docker rm $(docker container ls -aq --filter="name=edu")
# or 
PS> docker rm $(docker ps -aq --filter="name=edu")

rmi(删除镜像)

# 删除一个或者多个镜像
PS> docker rmi <image1_NameOrId> [<image2_NameOrId> ... <imageN_NameOrId>]

要批量删除这些带 edu_ 前缀或者 _edu 后缀的,需要通过匹配

# Powershell
# ^edu_: 表示匹配 edu_开头的
# _edu$: 表示匹配 _edu 结尾的
# :{{.Tag}}: 这个是格式化标签的,带上了会显示标签, 例如: nging:latest
PS> docker rmi $(docker images --format "{{.Repository}}[:{{.Tag}}]" | findstr "^edu_ _edu$")
# Linux 或者 MacOS 上将 fintstr 换成 grep 还有用 grep 的正则就行了

Concepts

docker-desktop-data:

​ docker 创建的容器存放在这里,这个好像是 Windows 系统中,使用了 WSL 才会出现的,本质其实就是一个 系统虚拟机,只是比较特殊。

Refs:

  • what is docker-desktop-data -- Stack Overflow
  • Introducing the Docker Desktop WSL 2 Backend

Windows:

WSL:

win + e 打开explorer(资源管理器 )——> 在explorer(资源管理器)的地址栏输入 \\\\wsl$\\docker-desktop-data 打开 docker-desktop-data.

Containers:

​ 在上面说了 docker-desktop-data 是 docker 存放 containers 的虚拟机,一些 containers 的配置也是存放在这里的。

docker-desktop 19.03.13-beta2 开始 containers 的配置都放在这下面

\\\\wsl$\\docker-desktop-data\\version-pack-data\\community\\docker\\containers\\

在之前的版本所在的路径是

\\\\wsl$\\docker-desktop-data\\mnt\\wsl\\docker-desktop-data\\data\\docker

Refs:

  • docker containers config.v2.json -- Stack Overflow

Other:

Refs:

  • Modify Docker container startup configuration parameters
  • How do I assign a port mapping to an existing Docker container?
  • 修改Docker容器启动配置参数
  • 如何修改 docker 容器的启动参数
  • Docker 教程 -- 小菠萝测试笔记
  • 追加docker已运行容器添加或修改端口映射方法

[
    {
        "Id": "a380c63c4d7e66d30f5a5d21b969e8957a347a7001c808d63e83ef21e477b88b",
        "Created": "2021-06-01T10:05:04.654748Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 255,
            "Error": "",
            "StartedAt": "2021-06-05T03:30:07.0556693Z",
            "FinishedAt": "2021-06-07T01:01:19.9231296Z"
        },
        "Image": "sha256:d1a364dc548d5357f0da3268c888e1971bbdb957ee3f028fe7194f1d61c6fdee",
        "ResolvConfPath": "/var/lib/docker/containers/a380c63c4d7e66d30f5a5d21b969e8957a347a7001c808d63e83ef21e477b88b/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/a380c63c4d7e66d30f5a5d21b969e8957a347a7001c808d63e83ef21e477b88b/hostname",
        "HostsPath": "/var/lib/docker/containers/a380c63c4d7e66d30f5a5d21b969e8957a347a7001c808d63e83ef21e477b88b/hosts",
        "LogPath": "/var/lib/docker/containers/a380c63c4d7e66d30f5a5d21b969e8957a347a7001c808d63e83ef21e477b88b/a380c63c4d7e66d30f5a5d21b969e8957a347a7001c808d63e83ef21e477b88b-json.log",
        "Name": "/nginx",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                // 例如 F:\\\\test\\\\projects
                "<实际目录的绝对路径>:/home/www"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "9002"
                    }
                ]
            },
            "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": [
                "/php-fpm:/nginx/php-fpm"
            ],
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                26,
                119
            ],
            "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/1beca78f1781901ac8d59dfc5aa90369db80d35087fc99fb2eeac34a68336098-init/diff:/var/lib/docker/overlay2/9891c32733210d1d3dabfc7e5a6e39da3e72b8b6a37d44a2b5ac3625965fb1cf/diff:/var/lib/docker/overlay2/12bd6576abf47717d1aa00f5e589a668f333a6212aa2f6f468b74d64254d9095/diff:/var/lib/docker/overlay2/fc917caf25c117a3c384baa71c5d71d60e1e95456f0cd3494370422c18dbceec/diff:/var/lib/docker/overlay2/051e1353b7545564b93c7830bfaa72e8a9dc1c43aaf5d49b1181502219cda043/diff:/var/lib/docker/overlay2/61299a683b86efab5625f6a4d3cee81ba4e8536063ada2529e46a267c27fd998/diff:/var/lib/docker/overlay2/91a8a75c4949ccd29cda9ab7844c255b4765537d9f6e967ca119f9dd3a95fa79/diff",
                "MergedDir": "/var/lib/docker/overlay2/1beca78f1781901ac8d59dfc5aa90369db80d35087fc99fb2eeac34a68336098/merged",
                "UpperDir": "/var/lib/docker/overlay2/1beca78f1781901ac8d59dfc5aa90369db80d35087fc99fb2eeac34a68336098/diff",
                "WorkDir": "/var/lib/docker/overlay2/1beca78f1781901ac8d59dfc5aa90369db80d35087fc99fb2eeac34a68336098/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "bind",
                // 例如 F:\\\\test\\\\projects
                "Source": "<实例目录的绝对路径>",
                "Destination": "/home/www",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "a380c63c4d7e",
            "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.0",
                "NJS_VERSION=0.5.3",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers \\u003cdocker-maint@nginx.com\\u003e"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "0f3f569dce91a16751c170f91ef9c8c128c757f86dff4e39f8ab58ae686f4edb",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "9002"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "9002"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/0f3f569dce91",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "553e63fa029a7dc7e123c74b330830033fdcc2a409baae5745e3875d17d6d580",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "c8af3e9943e0555af10ad6436ec37906039780a897e6ed0c0eb1655c0847f65e",
                    "EndpointID": "553e63fa029a7dc7e123c74b330830033fdcc2a409baae5745e3875d17d6d580",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

以上是关于Docker 学习的主要内容,如果未能解决你的问题,请参考以下文章

markdown docker-compose片段

sh Docker片段

IOS开发-OC学习-常用功能代码片段整理

java SpringRetry学习的代码片段

python 机器学习有用的代码片段

学习笔记:python3,代码片段(2017)