1、镜像管理命令

1、查看当前的镜像

1、查看当前的镜像
[root@node1 wordpress]# docker images
REPOSITORY     TAG            IMAGE ID       CREATED         SIZE
nginx          v1             a80567189207   6 days ago      141MB
bjbfd/nginx    latest         605c77e624dd   17 months ago   141MB
bjbfd/nginx    v1             605c77e624dd   17 months ago   141MB
nginx          latest         605c77e624dd   17 months ago   141MB
wordpress      latest         c3c92cc3dcb1   17 months ago   616MB
mariadb        10.6.4-focal   12e05d5da3c5   19 months ago   409MB
bjbfd/stress   latest         89e5b79daa74   7 years ago     215MB

2、查看image命令

[root@node1 wordpress]# docker image --help

Usage:  docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Download an image from a registry
  push        Upload an image to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

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

3、下载镜像(新增)

[root@node1 wordpress]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
Digest: sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
说明 : 
 nginx : 镜像名
 latest : 镜像版本

4、查看镜像列表(列表查询)

docker images同等docker image ls
[root@node1 wordpress]# docker image ls
REPOSITORY     TAG            IMAGE ID       CREATED         SIZE
bjbfd/nginx    latest         605c77e624dd   17 months ago   141MB
bjbfd/nginx    v1             605c77e624dd   17 months ago   141MB
nginx          latest         605c77e624dd   17 months ago   141MB
wordpress      latest         c3c92cc3dcb1   17 months ago   616MB
mariadb        10.6.4-focal   12e05d5da3c5   19 months ago   409MB
bjbfd/stress   latest         89e5b79daa74   7 years ago     215MB
说明 :
REPOSITORY : 表示镜像的仓库源
TAG : 镜像的标签
IMAGE ID : ID
CREATED : 镜像创建事件
SIZE : 镜像大小

5、查看镜像列表(列表查询)

docker images 等同于 docker image ls
[root@node1 ~]# docker image ls
REPOSITORY     TAG            IMAGE ID       CREATED         SIZE
bjbfd/nginx    latest         605c77e624dd   17 months ago   141MB
bjbfd/nginx    v1             605c77e624dd   17 months ago   141MB
nginx          latest         605c77e624dd   17 months ago   141MB
wordpress      latest         c3c92cc3dcb1   17 months ago   616MB
mariadb        10.6.4-focal   12e05d5da3c5   19 months ago   409MB
bjbfd/stress   latest         89e5b79daa74   7 years ago     215MB

说明 :
REPOSITORY : 表示镜像的仓库源
TAG : 镜像的标签
IMAGE ID : 镜像ID
CREATED : 镜像创建时间
SIZE : 镜像大小
同一个仓库源可以有多个TAG,代表这个仓库源的不同版本,我们使用REPOSITORY:TAG来定义不同的镜像

6、运行容器

[root@node1 ~]# docker run -itd nginx:latest
0243fb0c27018ecba95d0a4afafa452017b1e91cb3b62568a7b2e322038a67b2
说明 :
-i : 交互式操作
-t : 终端
-d : 守护进程运行
nginx:latest : 镜像

7、查看镜像详情(详情查询)

docker image inspect nginx:latest
[root@node1 ~]# docker image inspect nginx:latest
[
    {
        "Id": "sha256:605c77e624ddb75e6110f997c58876baa13f8754486b461117934b24a9dc3a85",
        "RepoTags": [
            "bjbfd/nginx:latest",
            "bjbfd/nginx:v1",
            "nginx:latest"
        ],
        "RepoDigests": [
            "bjbfd/nginx@sha256:ee89b00528ff4f02f2405e4ee221743ebc3f8e8dd0bfd5c4c20a2fa2aaa7ede3",
            "nginx@sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2021-12-29T19:28:29.892199479Z",
        "Container": "ca3e48389f7160bc9d9a892d316fcbba459344ee3679998739b1c3cd8e56f7da",
        "ContainerConfig": {
            "Hostname": "ca3e48389f71",
            "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.5",
                "NJS_VERSION=0.7.1",
                "PKG_RELEASE=1~bullseye"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"nginx\" \"-g\" \"daemon off;\"]"
            ],
            "Image": "sha256:82941edee2f4d17c55563bb926387c3ae39fa1a99777f088bc9d3db885192209",
            "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.5",
                "NJS_VERSION=0.7.1",
                "PKG_RELEASE=1~bullseye"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "sha256:82941edee2f4d17c55563bb926387c3ae39fa1a99777f088bc9d3db885192209",
            "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": 141479488,
        "VirtualSize": 141479488,
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/b00f6bf28e2dc408c796f09ad94d3f28c64e0a28cbdd6964087e2b26228b2328/diff:/var/lib/docker/overlay2/ca904171aa0883178d573b413ca24013e624e90395197a2e4914ebbae8388e7d/diff:/var/lib/docker/overlay2/4885892662a64db663878aee6f36c32d8196195e47a20ff2e0680256e28c20ac/diff:/var/lib/docker/overlay2/4eb0162b58d4f18bca9c0d48fb39f275dfbf92a59227dc380b7d36f614b45a4e/diff:/var/lib/docker/overlay2/a8c3e0d43b8b27fd19a575c3051c9cea6450d39d8fbb58c3d34c7d8b898d3b97/diff",
                "MergedDir": "/var/lib/docker/overlay2/9d155c02707c57771128e397e6e43c9c9691a544e8e5749b87da9ebc5857f554/merged",
                "UpperDir": "/var/lib/docker/overlay2/9d155c02707c57771128e397e6e43c9c9691a544e8e5749b87da9ebc5857f554/diff",
                "WorkDir": "/var/lib/docker/overlay2/9d155c02707c57771128e397e6e43c9c9691a544e8e5749b87da9ebc5857f554/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f",
                "sha256:e379e8aedd4d72bb4c529a4ca07a4e4d230b5a1d3f7a61bc80179e8f02421ad8",
                "sha256:b8d6e692a25e11b0d32c5c3dd544b71b1085ddc1fddad08e68cbd7fda7f70221",
                "sha256:f1db227348d0a5e0b99b15a096d930d1a69db7474a1847acbc31f05e4ef8df8c",
                "sha256:32ce5f6a5106cc637d09a98289782edf47c32cb082dc475dd47cbf19a4f866da",
                "sha256:d874fd2bc83bb3322b566df739681fbd2248c58d3369cb25908d68e7ed6040a6"
            ]
        },
        "Metadata": {
            "LastTagTime": "2023-05-29T22:25:44.056009028+08:00"
        }
    }
]

ContainerConfig : 容器配置
GraphDriver : 镜像驱动
RootFS : Docker文件系统

8、查看镜像构建历史(历史查询)

[root@node1 ~]# docker image history 605c77e624dd
IMAGE          CREATED         CREATED BY                                       SIZE      COMMENT
605c77e624dd   17 months ago   /bin/sh -c #(nop)  CMD ["nginx" "-g" "daemon…   0B
<missing>      17 months ago   /bin/sh -c #(nop)  STOPSIGNAL SIGQUIT            0B
<missing>      17 months ago   /bin/sh -c #(nop)  EXPOSE 80                     0B
<missing>      17 months ago   /bin/sh -c #(nop)  ENTRYPOINT ["/docker-entr…   0B
<missing>      17 months ago   /bin/sh -c #(nop) COPY file:09a214a3e07c919a…   4.61kB
<missing>      17 months ago   /bin/sh -c #(nop) COPY file:0fd5fca330dcd6a7…   1.04kB
<missing>      17 months ago   /bin/sh -c #(nop) COPY file:0b866ff3fc1ef5b0…   1.96kB
<missing>      17 months ago   /bin/sh -c #(nop) COPY file:65504f71f5855ca0…   1.2kB
<missing>      17 months ago   /bin/sh -c set -x     && addgroup --system -…   61.1MB
<missing>      17 months ago   /bin/sh -c #(nop)  ENV PKG_RELEASE=1~bullseye    0B
<missing>      17 months ago   /bin/sh -c #(nop)  ENV NJS_VERSION=0.7.1         0B
<missing>      17 months ago   /bin/sh -c #(nop)  ENV NGINX_VERSION=1.21.5      0B
<missing>      17 months ago   /bin/sh -c #(nop)  LABEL maintainer=NGINX Do…   0B
<missing>      17 months ago   /bin/sh -c #(nop)  CMD ["bash"]                  0B
<missing>      17 months ago   /bin/sh -c #(nop) ADD file:09675d11695f65c55…   80.4MB

9、查看仓库镜像版本

image.png

10、删除镜像

[root@node1 ~]# docker rmi bjbfd/stress:latest
Untagged: bjbfd/stress:latest
Untagged: bjbfd/stress@sha256:9d78f7f2cda8f1d9e8014bb087f6c53ee964400493adcc1f8cc3515d7b25321d
Deleted: sha256:89e5b79daa74679427a7c5dc8e24c8716f2a649aee03d8eeaed700ce7e2f8c07
Deleted: sha256:1bae8237f7ac02fc5b42c0c87bc634fc689baad852f16adbc4a5db757f7fd1e9
Deleted: sha256:c9b25ca08023c9a9d6a5cc555770aacd71d413a70b2a5cdd39d6e070e4e65732
Deleted: sha256:89a5271a5486c5d5ff56be49c9867b1a7ef5cae3ef1e3fd1a2d7e714f78f5fab
Deleted: sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef

11、删除不再使用的镜像

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS     NAMES
0243fb0c2701   nginx:latest   "/docker-entrypoint.…"   13 minutes ago   Up 13 minutes   80/tcp    confident_noether
[root@node1 ~]# docker image prune
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y
Total reclaimed space: 0B
[root@node1 ~]# docker image prune
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y
Total reclaimed space: 0B
[root@node1 ~]# docker images
REPOSITORY    TAG            IMAGE ID       CREATED         SIZE
bjbfd/nginx   latest         605c77e624dd   17 months ago   141MB
bjbfd/nginx   v1             605c77e624dd   17 months ago   141MB
nginx         latest         605c77e624dd   17 months ago   141MB
wordpress     latest         c3c92cc3dcb1   17 months ago   616MB
mariadb       10.6.4-focal   12e05d5da3c5   19 months ago   409MB
[root@node1 ~]# docker image prune -a
WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y
Deleted Images:
untagged: bjbfd/nginx:latest
untagged: bjbfd/nginx:v1
untagged: bjbfd/nginx@sha256:ee89b00528ff4f02f2405e4ee221743ebc3f8e8dd0bfd5c4c20a2fa2aaa7ede3
untagged: wordpress:latest
untagged: wordpress@sha256:fc33b796b04162a0db2e9ea9b4c361a07058b21597b1317ad9ab3ea4593de241
deleted: sha256:c3c92cc3dcb1a903fed0374a837f38d716ae104d0e4c9705bddb53a76419534d
deleted: sha256:e03d610209901c4c643d9787f53e556f3a034ece25b597205d8333db2ff81872
deleted: sha256:d016493a41b04f201d91ac317b607a0fc2f87a8d825d6dfb6b8dc1bf2fba4efe
deleted: sha256:7904e413594a78ddb5e5909909e5c37255d7be1ada4b4bf16e33368200ddea2d
deleted: sha256:291dc2654c9399be32d82521744e650eb3d899d6356856dfd497f180782b76b8
deleted: sha256:2c7d4e23a0ce5d99dc09041e86f5bcdc2404d703e769189fddc8cc45322bbda9
deleted: sha256:d3e712f7ab059427794f7f209f448f94fc60dee3e4e40eb82cd99605ab55af3c
deleted: sha256:10ab8416164c9b2c408ac1317419e9dd113091f6290d33f73cf1cc9c9781fb2b
deleted: sha256:d61093d47caf389668eb96344afab2454620a5c586b1de3859e17d255a19ba89
deleted: sha256:3cccde4cd0f42cdd4b0a2c088a88785183e11b4e7c425ff4c4f54326e8e9764b
deleted: sha256:1053961a55147906b29c3be9c1186d5d9563db08c1e5b63c4e7b286f3dc043f6
deleted: sha256:1e1b1a779971b332e7e954d0219153cd320cdd27521a15a97da4151ef45e3d7d
deleted: sha256:682226507754fd5f59ce67ff0801c9df859b106cd5a3db24defb073650cf7fb5
deleted: sha256:782d3b9de219e51086f1cab57778a10e7a88784008cb8b629e02e173c6683cc1
deleted: sha256:c3d02f3fbe0afe22bc647345d3d217f2a26133062c1ada547645afdd1243cacc
deleted: sha256:eec2c2512d15a9611866e4ddf17af2c480009045dbca2a3a22f30becb2050ae2
deleted: sha256:8c360a4ebc0a45f7de7228d7d4ae497ddcf9c73218c5b4e628188f22cae1c663
deleted: sha256:ee5205a969dcf1186060d0b8719db08647c3f86ccf33770b83b6ef1c989258e1
deleted: sha256:6b322a9c05d5df05b87396796502965c8e6212aeb07ced777ed206f660c7a098
deleted: sha256:c688355f4fe75990c63df6c38a962e3cadfaa0d84c826a920cf2a43fa0975270
deleted: sha256:895915dadaf75a7370a1817ba4e54f0ee5b329b81aab80a3552736c10b065fc5
untagged: mariadb:10.6.4-focal
untagged: mariadb@sha256:c014ba1efc5dbd711d0520c7762d57807f35549de3414eb31e942a420c8a2ed2
deleted: sha256:12e05d5da3c5223e9877e8eb90d68560ff66cedcb955131061d60d093a908f0c
deleted: sha256:ffb9fb143b85a783ff0e83cf0c594c8fd6838b889dee7d14c0a2a3e0c9df419d
deleted: sha256:067860988e6658468a17d2d0d57fb3e74ef45bf3b38167a796f5bfa61d14ed4d
deleted: sha256:52da81964394b8f090e4e3405eb3478cbb274d84e023680b5eb21be463d4fb72
deleted: sha256:4bd99e1fe00faaa2737267cb775982ad444ad62999d37df6a9fa92f458d9f10c
deleted: sha256:9f4f0dd33c9816176e9bd3077cee199d0f14bd05ef5b7e2f01a80a1ea3d48316
deleted: sha256:46c59a61ed6209c1e6a55e8811345216f5dfe704d4411ba3e37e1cb345d7deeb
deleted: sha256:4bf277548ca07781855a8ce8c8b299a89fd5742151003f83053026e0b01f8470
deleted: sha256:715a1b962166ede06c7a0e87d068a4b686e6066e0eca5ecab6f4d6cfab2121fe
deleted: sha256:97ab3baee34d0c75ee10e65c63a06cbc87d20d695c17d14ad565d4ff1b8dc2ca
deleted: sha256:9f54eef412758095c8079ac465d494a2872e02e90bf1fb5f12a1641c0d1bb78b

Total reclaimed space: 944.5MB
[root@node1 ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    605c77e624dd   17 months ago   141MB

docker image prune -a 会清理掉所有不再运行的容器的镜像

12、备份镜像

[root@node1 ~]# docker save -o nginx.tar nginx:latest
[root@node1 ~]# ls
nginx.tar

13、加载镜像

[root@node1 ~]# docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
[root@node1 ~]# ls
nginx.tar
[root@node1 ~]# docker image load -i nginx.tar
Loaded image: nginx:latest
[root@node1 ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    605c77e624dd   17 months ago   141MB

14、导入镜像

[root@node1 ~]# docker image import nginx.tar
sha256:c1f8bc3f7d5a0882c590483936f9edf23f51e995e84dafaba301071f58cee6f3
[root@node1 ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
<none>       <none>    c1f8bc3f7d5a   5 seconds ago   146MB

15、构建镜像

[root@node1 nginx]# cat Dockerfile
FROM nginx
RUN echo '这是一个本地构建的nginx镜像' > /usr/share/nginx/html/index.html
[root@node1 nginx]# docker build -t bjbfd/nginx:v1 .
[+] Building 0.0s (6/6) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                0.0s
 => => transferring dockerfile: 133B                                                                                                                                                                0.0s
 => [internal] load .dockerignore                                                                                                                                                                   0.0s
 => => transferring context: 2B                                                                                                                                                                     0.0s
 => [internal] load metadata for docker.io/library/nginx:latest                                                                                                                                     0.0s
 => [1/2] FROM docker.io/library/nginx                                                                                                                                                              0.0s
 => CACHED [2/2] RUN echo '这是一个本地构建的nginx镜像' > /usr/share/nginx/html/index.html                                                                                                                     0.0s
 => exporting to image                                                                                                                                                                              0.0s
 => => exporting layers                                                                                                                                                                             0.0s
 => => writing image sha256:a805671892075472b21360ead42fb53a2ad798b0ab56bab450c52d428ce1441b                                                                                                        0.0s
 => => naming to docker.io/bjbfd/nginx:v1                                                                                                                                                           0.0s
[root@node1 nginx]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   6 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB

-t : 指定要创建的目标镜像名
. : Dockerfile文件所在的目录,可以指定Dockerfile的绝对路径

16、给镜像打Tag

[root@node1 nginx]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   6 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 nginx]# docker image tag bjbfd/nginx:v1 bjbfd/nginx:v2
[root@node1 nginx]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   6 days ago      141MB
bjbfd/nginx   v2        a80567189207   6 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB

17、推送镜像仓库

[root@node1 nginx]# docker push bjbfd/nginx:v1
The push refers to repository [docker.io/bjbfd/nginx]
b84ae2a5c7a5: Pushed
d874fd2bc83b: Layer already exists
32ce5f6a5106: Layer already exists
f1db227348d0: Layer already exists
b8d6e692a25e: Layer already exists
e379e8aedd4d: Layer already exists
2edcec3590a4: Layer already exists
v1: digest: sha256:76d0541f94a712a86c3e1c5683cc0e03ed5e500360a73dcaa7b085ff2a540c04 size: 1777

2、镜像管理命令

1、运行容器

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   7 days ago      141MB
bjbfd/nginx   v2        a80567189207   7 days ago      141MB
bjbfd/nginx   v3        a80567189207   7 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 ~]# docker run -itd nginx:latest]
docker: invalid reference format.
See 'docker run --help'.
[root@node1 ~]# docker run -itd nginx:latest
d7ac05b931e96fc4c5a15ca82cb7b6a093f9f28fd70debc9c364ac6f85a52ecf
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
d7ac05b931e9   nginx:latest   "/docker-entrypoint.…"   3 seconds ago   Up 2 seconds   80/tcp    cranky_hertz

2、创建一个容器

[root@node1 ~]# docker create nginx:latest
983199af829ab0125b246a6e311823ec908628fd91276c3b7d464716a3edb30a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS    PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   3 seconds ago   Created             gallant_boyd
[root@node1 ~]# docker exec -it 983199af829a /bin/bash
Error response from daemon: Container 983199af829ab0125b246a6e311823ec908628fd91276c3b7d464716a3edb30a is not running
注意 : 发现了没有,创建完毕容器,是不能docker exec -it进入容器的,发现状态是CREATED状态,是需要进行start的才能运行

3、启动容器

[root@node1 ~]# docker start 983199af829a
983199af829a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS          PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   2 minutes ago   Up 14 seconds   80/tcp    gallant_boyd
[root@node1 ~]# docker exec -it 983199af829a /bin/bash
root@983199af829a:/# curl 127.0.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
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>

4、停止容器

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS              PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   3 minutes ago   Up About a minute   80/tcp    gallant_boyd
[root@node1 ~]# docker stop 983199af829a
983199af829a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS                     PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   3 minutes ago   Exited (0) 3 seconds ago             gallant_boyd
[root@node1 ~]# docker start 983199af829a
983199af829a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   4 minutes ago   Up 2 seconds   80/tcp    gallant_boyd

注意 : 发现停止容器之后还是可以进行start的

5、查看容器列表

docker ps -a和docker container ls是相同的命令,都可以

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS              PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   5 minutes ago   Up About a minute   80/tcp    gallant_boyd
[root@node1 ~]# docker container ls
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS              PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   5 minutes ago   Up About a minute   80/tcp    gallant_boyd

6、重启容器

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   6 minutes ago   Up 2 minutes   80/tcp    gallant_boyd
[root@node1 ~]# docker restart 983199af829a
983199af829a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   6 minutes ago   Up 2 seconds   80/tcp    gallant_boyd

7、杀死容器

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS              PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   7 minutes ago   Up About a minute   80/tcp    gallant_boyd
[root@node1 ~]# docker kill 983199af829a
983199af829a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS                       PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   8 minutes ago   Exited (137) 9 seconds ago             gallant_boyd
[root@node1 ~]# docker start 983199af829a
983199af829a
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
983199af829a   nginx:latest   "/docker-entrypoint.…"   8 minutes ago   Up 5 seconds   80/tcp    gallant_boyd

注意 : kill掉的容器也是可以重新start的,只是标识是强制退出还是柔性的退出而已

8、挂起容器

[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   7 days ago      141MB
bjbfd/nginx   v2        a80567189207   7 days ago      141MB
bjbfd/nginx   v3        a80567189207   7 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 ~]# docker run -itd -p 8888:80 nginx:latest
5ea91b92d19307772aa39bbdd73b822104e89d62a58b7d4d8a3cb76b15286dcc
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                   NAMES
5ea91b92d193   nginx:latest   "/docker-entrypoint.…"   6 minutes ago   Up 6 minutes   0.0.0.0:8888->80/tcp, :::8888->80/tcp   flamboyant_shannon
[root@node1 ~]# curl 127.0.0.1:8888
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
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>
[root@node1 ~]# docker pause 5ea91b92d193
5ea91b92d193
[root@node1 ~]# curl 127.0.0.1:8888
^C
[root@node1 ~]#
注意 : 其实就是让容器不堆外服务

9、接挂容器

[root@node1 ~]# docker unpause 5ea91b92d193
5ea91b92d193
[root@node1 ~]# curl 127.0.0.1:8888
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
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>

10、删除容器

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                   NAMES
5ea91b92d193   nginx:latest   "/docker-entrypoint.…"   9 minutes ago   Up 9 minutes   0.0.0.0:8888->80/tcp, :::8888->80/tcp   flamboyant_shannon
[root@node1 ~]# docker rm -f 5ea91b92d193
5ea91b92d193

11、删除没有用容器

[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   7 days ago      141MB
bjbfd/nginx   v2        a80567189207   7 days ago      141MB
bjbfd/nginx   v3        a80567189207   7 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 ~]# docker run -itd nginx:latest
d777a7f12f3e1fe3ad5e2b50e119a25a6381cbb86862dc2ec5d7b950b7bfb2f6
[root@node1 ~]# docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Total reclaimed space: 0B
[root@node1 ~]# docker stop d777a7f12f3e1fe3ad5e2b50e119a25a6381cbb86862dc2ec5d7b950b7bfb2f6
d777a7f12f3e1fe3ad5e2b50e119a25a6381cbb86862dc2ec5d7b950b7bfb2f6
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS                     PORTS     NAMES
d777a7f12f3e   nginx:latest   "/docker-entrypoint.…"   19 seconds ago   Exited (0) 2 seconds ago             keen_galois
[root@node1 ~]# docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
d777a7f12f3e1fe3ad5e2b50e119a25a6381cbb86862dc2ec5d7b950b7bfb2f6

Total reclaimed space: 1.093kB
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@node1 ~]#

12、查看容器日志

[root@node1 ~]# docker logs -n 100  e2d34d63ca4c
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/06/03 07:47:03 [notice] 1#1: using the "epoll" event method
2023/06/03 07:47:03 [notice] 1#1: nginx/1.21.5
2023/06/03 07:47:03 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2023/06/03 07:47:03 [notice] 1#1: OS: Linux 3.10.0-1127.19.1.el7.x86_64
2023/06/03 07:47:03 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/06/03 07:47:03 [notice] 1#1: start worker processes
2023/06/03 07:47:03 [notice] 1#1: start worker process 31
2023/06/03 07:47:03 [notice] 1#1: start worker process 32

13、进入容器

[root@node1 ~]# docker exec -it e2d34d63ca4c /bin/bash
root@e2d34d63ca4c:/#

14、拷贝容器文件

将本地文件拷贝到容器中
[root@node1 ~]# ls
nginx.tar
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
e2d34d63ca4c   nginx:latest   "/docker-entrypoint.…"   3 minutes ago   Up 3 minutes   80/tcp    youthful_keller
[root@node1 ~]# docker cp nginx.tar e2d34d63ca4c:/
Successfully copied 146MB to e2d34d63ca4c:/
[root@node1 ~]# docker exec -it e2d34d63ca4c /bin/bash
root@e2d34d63ca4c:/# ls
bin  boot  dev    docker-entrypoint.d  docker-entrypoint.sh  etc    home  lib  lib64  media  mnt  nginx.tar  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@e2d34d63ca4c:/# ls nginx.tar
nginx.tar

将容器文件拷贝到本地
root@e2d34d63ca4c:/# touch test.txt
[root@node1 ~]# docker cp e2d34d63ca4c:/test.txt .
Successfully copied 1.54kB to /root/.
[root@node1 ~]# ls
nginx.tar  test.txt
[root@node1 ~]#

15、容器重命名

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
e2d34d63ca4c   nginx:latest   "/docker-entrypoint.…"   6 minutes ago   Up 6 minutes   80/tcp    youthful_keller
[root@node1 ~]# docker rename e2d34d63ca4c nginx_container
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
e2d34d63ca4c   nginx:latest   "/docker-entrypoint.…"   6 minutes ago   Up 6 minutes   80/tcp    nginx_container
[root@node1 ~]#

16、更新容器信息

[root@node1 ~]# docker update -m 128m --memory-swap -1 e2d34d63ca4c
e2d34d63ca4c

17、查看容器所占的资源

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS     NAMES
e2d34d63ca4c   nginx:latest   "/docker-entrypoint.…"   14 minutes ago   Up 14 minutes   80/tcp    nginx_container
[root@node1 ~]# docker stats e2d34d63ca4c
CONTAINER ID   NAME              CPU %     MEM USAGE / LIMIT   MEM %     NET I/O     BLOCK I/O       PIDS
e2d34d63ca4c   nginx_container   0.01%     2.094MiB / 128MiB   1.64%     656B / 0B   193kB / 4.1kB   3
CONTAINER ID   NAME              CPU %     MEM USAGE / LIMIT   MEM %     NET I/O     BLOCK I/O       PIDS

18、查看端口

[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        a80567189207   7 days ago      141MB
bjbfd/nginx   v2        a80567189207   7 days ago      141MB
bjbfd/nginx   v3        a80567189207   7 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 ~]# docker run -itd -p 8888:80 nginx:latest
7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                   NAMES
7f916ec2c2ad   nginx:latest   "/docker-entrypoint.…"   3 seconds ago   Up 2 seconds   0.0.0.0:8888->80/tcp, :::8888->80/tcp   charming_benz
[root@node1 ~]# docker port 7f916ec2c2ad
80/tcp -> 0.0.0.0:8888
80/tcp -> [::]:8888
[root@node1 ~]#

19、查看容器进程

[root@node1 ~]# docker top 7f916ec2c2ad
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                4007                3986                0                   16:03               pts/0               00:00:00            nginx: master process nginx -g daemon off;
101                 4051                4007                0                   16:03               pts/0               00:00:00            nginx: worker process
101                 4052                4007                0                   16:03               pts/0               00:00:00            nginx: worker process

20、从容器创建一个新的镜像

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                   NAMES
7f916ec2c2ad   nginx:latest   "/docker-entrypoint.…"   4 minutes ago   Up 4 minutes   0.0.0.0:8888->80/tcp, :::8888->80/tcp   charming_benz
[root@node1 ~]# docker commit -a "journey" -m "add by journey" 7f916ec2c2ad
sha256:6d4beeb788dda4d53f991789736373a4488f048bd6f34236aa44f0e7e80c7143
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                   NAMES
7f916ec2c2ad   nginx:latest   "/docker-entrypoint.…"   4 minutes ago   Up 4 minutes   0.0.0.0:8888->80/tcp, :::8888->80/tcp   charming_benz
[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
<none>        <none>    6d4beeb788dd   12 seconds ago   141MB
bjbfd/nginx   v1        a80567189207   7 days ago       141MB
bjbfd/nginx   v2        a80567189207   7 days ago       141MB
bjbfd/nginx   v3        a80567189207   7 days ago       141MB
nginx         latest    605c77e624dd   17 months ago    141MB

21、查看容器信息

[root@node1 ~]# docker inspect 7f916ec2c2ad
[
    {
        "Id": "7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c",
        "Created": "2023-06-03T08:03:57.016540909Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 4007,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2023-06-03T08:03:57.268472187Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:605c77e624ddb75e6110f997c58876baa13f8754486b461117934b24a9dc3a85",
        "ResolvConfPath": "/var/lib/docker/containers/7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c/hostname",
        "HostsPath": "/var/lib/docker/containers/7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c/hosts",
        "LogPath": "/var/lib/docker/containers/7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c/7f916ec2c2ad7c0cf8a8e90101edda75e152885db88f6316e5317f05e408344c-json.log",
        "Name": "/charming_benz",
        "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": "8888"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                28,
                201
            ],
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "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/8e6dca3763335b09a41eaa6d81211cebaee9602c65002329a8489b21b55f84d0-init/diff:/var/lib/docker/overlay2/9d155c02707c57771128e397e6e43c9c9691a544e8e5749b87da9ebc5857f554/diff:/var/lib/docker/overlay2/b00f6bf28e2dc408c796f09ad94d3f28c64e0a28cbdd6964087e2b26228b2328/diff:/var/lib/docker/overlay2/ca904171aa0883178d573b413ca24013e624e90395197a2e4914ebbae8388e7d/diff:/var/lib/docker/overlay2/4885892662a64db663878aee6f36c32d8196195e47a20ff2e0680256e28c20ac/diff:/var/lib/docker/overlay2/4eb0162b58d4f18bca9c0d48fb39f275dfbf92a59227dc380b7d36f614b45a4e/diff:/var/lib/docker/overlay2/a8c3e0d43b8b27fd19a575c3051c9cea6450d39d8fbb58c3d34c7d8b898d3b97/diff",
                "MergedDir": "/var/lib/docker/overlay2/8e6dca3763335b09a41eaa6d81211cebaee9602c65002329a8489b21b55f84d0/merged",
                "UpperDir": "/var/lib/docker/overlay2/8e6dca3763335b09a41eaa6d81211cebaee9602c65002329a8489b21b55f84d0/diff",
                "WorkDir": "/var/lib/docker/overlay2/8e6dca3763335b09a41eaa6d81211cebaee9602c65002329a8489b21b55f84d0/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "7f916ec2c2ad",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.5",
                "NJS_VERSION=0.7.1",
                "PKG_RELEASE=1~bullseye"
            ],
            "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": "0277334aaf076407c0d61b71d9db0832af2f4d36ca0233e986e093a76d4d5e99",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "8888"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "8888"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/0277334aaf07",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "cb94381c2ee768a2b16e3337df23140f243721ce071eedd8ac78eba010a12669",
            "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": "5ceeded040a83e20aa47366ee6fb8c6abb7cdf048f9eb235fec7b4247292c1b4",
                    "EndpointID": "cb94381c2ee768a2b16e3337df23140f243721ce071eedd8ac78eba010a12669",
                    "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
                }
            }
        }
    }
]

3、仓库管理命令

1、Docker Hub

仓库(Repository)是集中存放镜像的地方。Docker官方维护了一个公共仓库Docker Hub。大部分需求都可以通过在Docker Hub中直接下载镜像来实现

2、Docker Hub注册

image.png

3、Docker Hub 登录

[root@node1 ~]# docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: bjbfd
Password:
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

4、Docker Hub 退出

[root@node1 ~]# docker logout
Removing login credentials for https://index.docker.io/v1/

5、镜像搜索

[root@node1 ~]# docker search nginx
NAME                                              DESCRIPTION                                      STARS     OFFICIAL   AUTOMATED
nginx                                             Official build of Nginx.                         18593     [OK]
unit                                              Official build of NGINX Unit: Universal Web …   5         [OK]
nginxproxy/nginx-proxy                            Automated Nginx reverse proxy for docker con…   88
nginxproxy/acme-companion                         Automated ACME SSL certificate generation fo…   113
bitnami/nginx                                     Bitnami nginx Docker Image                       164                  [OK]
bitnami/nginx-ingress-controller                  Bitnami Docker Image for NGINX Ingress Contr…   29                   [OK]
ubuntu/nginx                                      Nginx, a high-performance reverse proxy & we…   95
nginxproxy/docker-gen                             Generate files from docker container meta-da…   12
kasmweb/nginx                                     An Nginx image based off nginx:alpine and in…   6
rancher/nginx-ingress-controller                                                                   11
rancher/nginx-ingress-controller-defaultbackend                                                    2
bitnami/nginx-exporter                                                                             3
rancher/nginx                                                                                      2
rapidfort/nginx-ib                                RapidFort optimized, hardened image for NGIN…   10
rapidfort/nginx                                   RapidFort optimized, hardened image for NGINX    14
vmware/nginx-photon                                                                                1
bitnami/nginx-ldap-auth-daemon                                                                     3
rapidfort/nginx-official                          RapidFort optimized, hardened image for NGIN…   10
vmware/nginx                                                                                       2
rancher/nginx-conf                                                                                 0
linuxserver/nginx                                 An Nginx container, brought to you by LinuxS…   201
nginxproxy/forego                                 Foreman in Go                                    0
privatebin/nginx-fpm-alpine                       PrivateBin running on an Nginx, php-fpm & Al…   72                   [OK]
bitnami/nginx-intel                                                                                1
bitnamicharts/nginx                                                                                0
[root@node1 ~]#

6、下载镜像到本地

[root@node1 ~]# docker pull nginx:1.16.0
1.16.0: Pulling from library/nginx
9fc222b64b0a: Pull complete
30e9fc7d9c5b: Pull complete
4b3a8aeaa40e: Pull complete
Digest: sha256:3e373fd5b8d41baeddc24be311c5c6929425c04cabf893b874ac09b72a798010
Status: Downloaded newer image for nginx:1.16.0
docker.io/library/nginx:1.16.0
[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
<none>        <none>    6d4beeb788dd   17 hours ago    141MB
bjbfd/nginx   v1        a80567189207   7 days ago      141MB
bjbfd/nginx   v2        a80567189207   7 days ago      141MB
bjbfd/nginx   v3        a80567189207   7 days ago      141MB
nginx         latest    605c77e624dd   17 months ago   141MB
nginx         1.16.0    ae893c58d83f   3 years ago     109MB
[root@node1 ~]#

7、推送镜像

[root@node1 nginx]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED       SIZE
bjbfd/nginx   v4        a80567189207   7 days ago    141MB
nginx         1.16.0    ae893c58d83f   3 years ago   109MB
[root@node1 nginx]# docker push bjbfd/nginx:v4
The push refers to repository [docker.io/bjbfd/nginx]
b84ae2a5c7a5: Layer already exists
d874fd2bc83b: Layer already exists
32ce5f6a5106: Layer already exists
f1db227348d0: Layer already exists
b8d6e692a25e: Layer already exists
e379e8aedd4d: Layer already exists
2edcec3590a4: Layer already exists
v4: digest: sha256:76d0541f94a712a86c3e1c5683cc0e03ed5e500360a73dcaa7b085ff2a540c04 size: 1777

4、网络管理命令

1、网络管理帮助文档

[root@node1 nginx]# docker network --help

Usage:  docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

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

2、新建网络

[root@node1 nginx]# docker network create journey_network
13c87663bccf0eb404edc4441c9cb819072faeebfceed4ad6bf07b2ca1f8f3fc

3、查看网络列表

[root@node1 nginx]# docker network ls
NETWORK ID     NAME                DRIVER    SCOPE
743d1d364d1d   bridge              bridge    local
4882bc599fcc   docker_gwbridge     bridge    local
06d4d17eacbf   host                host      local
zylych55j9kk   ingress             overlay   swarm
13c87663bccf   journey_network     bridge    local
276755b5e003   none                null      local
0e99973cc931   wordpress_default   bridge    local

4、删除网络

[root@node1 nginx]# docker network rm journey_network
journey_network

5、删除未使用的网络

[root@node1 nginx]# docker network prune
WARNING! This will remove all custom networks not used by at least one container.
Are you sure you want to continue? [y/N] y
Deleted Networks:
wordpress_defaul

6、容器的网络设置

[root@node1 nginx]# docker network ls
NETWORK ID     NAME              DRIVER    SCOPE
743d1d364d1d   bridge            bridge    local
4882bc599fcc   docker_gwbridge   bridge    local
06d4d17eacbf   host              host      local
zylych55j9kk   ingress           overlay   swarm
f905066b895c   journey_network   bridge    local
276755b5e003   none              null      local
[root@node1 nginx]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS     NAMES
d92e103aae40   ae893c58d83f   "nginx -g 'daemon of…"   48 seconds ago   Up 47 seconds   80/tcp    unruffled_curie
[root@node1 nginx]# docker inspect d92e103aae40
[
    {
        "Id": "d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2",
        "Created": "2023-06-04T01:41:25.482832723Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 2515,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2023-06-04T01:41:25.735005762Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:ae893c58d83fe2bd391fbec97f5576c9a34fea55b4ee9daf15feb9620b14b226",
        "ResolvConfPath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/hostname",
        "HostsPath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/hosts",
        "LogPath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2-json.log",
        "Name": "/unruffled_curie",
        "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,
            "ConsoleSize": [
                28,
                201
            ],
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "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/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023-init/diff:/var/lib/docker/overlay2/50fbc6f52a459bf5fa29df4d85fd3e50a59d1aaa101fb43134df9438dcc37fcd/diff:/var/lib/docker/overlay2/6540b047fa36aa6293df76649dd30e54cc05becec17471951e8d8c23de789a80/diff:/var/lib/docker/overlay2/578b8f6e57cd1ed1b68a3de2d1986f5ef64fb917c5ddf3b759a5790ea9a61439/diff",
                "MergedDir": "/var/lib/docker/overlay2/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023/merged",
                "UpperDir": "/var/lib/docker/overlay2/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023/diff",
                "WorkDir": "/var/lib/docker/overlay2/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d92e103aae40",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.16.0",
                "NJS_VERSION=0.3.1",
                "PKG_RELEASE=1~stretch"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "ae893c58d83f",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "bad2c90004b767ec71885ff9128aaecb16b98dbd2d6aa4eaa259254ea0f0856f",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/bad2c90004b7",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "c4bab2cdcb8e5750eabd7b6347ca6105884b7a016692d85571fc72932613b881",
            "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": "743d1d364d1d930cc86d311ec72231e9452077128bfdad7af65154d9f04002a3",
                    "EndpointID": "c4bab2cdcb8e5750eabd7b6347ca6105884b7a016692d85571fc72932613b881",
                    "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
                }
            }
        }
    }
] 

注意 : 
 "NetworkID": "743d1d364d1d930cc86d311ec72231e9452077128bfdad7af65154d9f04002a3" 可以看到默认走的是 743d1d364d1d   bridge            bridge    local 的网络,如果想换一个我们自定义的网络,怎么办呢?

[root@node1 nginx]# docker network connect journey_network d92e103aae40
[root@node1 nginx]# docker inspect d92e103aae40
[
    {
        "Id": "d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2",
        "Created": "2023-06-04T01:41:25.482832723Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 2515,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2023-06-04T01:41:25.735005762Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:ae893c58d83fe2bd391fbec97f5576c9a34fea55b4ee9daf15feb9620b14b226",
        "ResolvConfPath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/hostname",
        "HostsPath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/hosts",
        "LogPath": "/var/lib/docker/containers/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2/d92e103aae404fe3e4944d0eb4bb55fd1483b5de8c295d15599489acede221e2-json.log",
        "Name": "/unruffled_curie",
        "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,
            "ConsoleSize": [
                28,
                201
            ],
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "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/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023-init/diff:/var/lib/docker/overlay2/50fbc6f52a459bf5fa29df4d85fd3e50a59d1aaa101fb43134df9438dcc37fcd/diff:/var/lib/docker/overlay2/6540b047fa36aa6293df76649dd30e54cc05becec17471951e8d8c23de789a80/diff:/var/lib/docker/overlay2/578b8f6e57cd1ed1b68a3de2d1986f5ef64fb917c5ddf3b759a5790ea9a61439/diff",
                "MergedDir": "/var/lib/docker/overlay2/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023/merged",
                "UpperDir": "/var/lib/docker/overlay2/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023/diff",
                "WorkDir": "/var/lib/docker/overlay2/4933d9dc5e21b63cf7216cabe44d41eb9c8a1a924527f3e3e02332fc62987023/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d92e103aae40",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.16.0",
                "NJS_VERSION=0.3.1",
                "PKG_RELEASE=1~stretch"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "ae893c58d83f",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "bad2c90004b767ec71885ff9128aaecb16b98dbd2d6aa4eaa259254ea0f0856f",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/bad2c90004b7",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "c4bab2cdcb8e5750eabd7b6347ca6105884b7a016692d85571fc72932613b881",
            "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": "743d1d364d1d930cc86d311ec72231e9452077128bfdad7af65154d9f04002a3",
                    "EndpointID": "c4bab2cdcb8e5750eabd7b6347ca6105884b7a016692d85571fc72932613b881",
                    "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
                },
                "journey_network": {
                    "IPAMConfig": {},
                    "Links": null,
                    "Aliases": [
                        "d92e103aae40"
                    ],
                    "NetworkID": "f905066b895cd55108dd0b8a5117408e2ac7f78fbe2038761ca075f02f144a03",
                    "EndpointID": "82a6740dbaed45e4e36438b605c9a059580f35760c79fe353fa4b689666458a7",
                    "Gateway": "172.20.0.1",
                    "IPAddress": "172.20.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:14:00:02",
                    "DriverOpts": {}
                }
            }
        }
    }
]

注意 : 
 "NetworkID": "f905066b895cd55108dd0b8a5117408e2ac7f78fbe2038761ca075f02f144a03" 是不是就是我们自定义的 f905066b895c   journey_network   bridge    local 的网络

7、容器的网络删除

[root@node1 nginx]# docker network disconnect journey_network d92e103aae40

注意 : 发现删除自定义的网络,就是默认的网络了,就是之前默认设置的网络(743d1d364d1d bridge bridge local)

5、存储卷管理

1、docker持久化测试

[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED       SIZE
bjbfd/nginx   v4        a80567189207   8 days ago    141MB
nginx         1.16.0    ae893c58d83f   3 years ago   109MB
[root@node1 ~]# docker run -itd nginx:1.16.0
d24cfc2451e1f2d789ec5813a15d43d2bca4def4ed21f26fea1379ed2be4d0c4
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS     NAMES
d24cfc2451e1   nginx:1.16.0   "nginx -g 'daemon of…"   3 seconds ago   Up 2 seconds   80/tcp    hardcore_dewdney
[root@node1 ~]# docker exec -it d24cfc2451e1 /bin/bash
root@d24cfc2451e1:/# ls
bin  boot  dev    etc  home  lib    lib64  media  mnt  opt    proc  root  run  sbin  srv  sys  tmp  usr  var
root@d24cfc2451e1:/# touch my.txt
root@d24cfc2451e1:/# cat > my.txt
aaa
^C
root@d24cfc2451e1:/# cat my.txt
aaa
root@d24cfc2451e1:/# ls
bin  boot  dev    etc  home  lib    lib64  media  mnt  my.txt  opt    proc  root  run  sbin  srv  sys  tmp  usr  var
root@d24cfc2451e1:/# exit
exit
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS     NAMES
d24cfc2451e1   nginx:1.16.0   "nginx -g 'daemon of…"   45 seconds ago   Up 44 seconds   80/tcp    hardcore_dewdney
[root@node1 ~]# docker stop d24cfc2451e1
d24cfc2451e1
[root@node1 ~]# docker start d24cfc2451e1
d24cfc2451e1
[root@node1 ~]# docker exec -it d24cfc2451e1 /bin/bash
root@d24cfc2451e1:/# cat my.txt
aaa
root@d24cfc2451e1:/#

测试发现,docker的容器是支持文件持久化的。停止再启动容器,文件是不会丢失的

2、删除再通过镜像启动容器,文件是否丢失测试

发现,如果我们删除容器,再通过镜像启动容器,原来容器里面的my.txt文件丢失

2、docker volume

1、docker数据持久化

  • bind mount : 挂载任意目录或文件
  • volumns : 固定路径的目录,docker管理
  • tmpfs mounts : 存放宿主机内存中
    image.png

2、docker容器共享

image.png

3、docker数据持久化应用

3.1、bind mount

[root@node1 ~]# docker run -itd --name nginx_node1 -v /data/nginx/:/usr/share/nginx/html nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
a2abf6c4d29d: Already exists
a9edb18cadd1: Already exists
589b7251471a: Already exists
186b1aaa4aa6: Already exists
b4df32aa5a72: Already exists
a0bcbecc962e: Already exists
Digest: sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
Status: Downloaded newer image for nginx:latest
0a62e4026a157ae1a267991253f9f54371a0e3d706a2c36f3a9698949ae81df4
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED          STATUS          PORTS     NAMES
0a62e4026a15   nginx     "/docker-entrypoint.…"   36 seconds ago   Up 35 seconds   80/tcp    nginx_node1
[root@node1 ~]# docker exec -it 0a62e4026a15 /bin/bash
root@0a62e4026a15:/# curl 127.0.0.1
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.21.5</center>
</body>
</html>
[root@node1 ~]# cd /data/nginx/
[root@node1 nginx]# ls
[root@node1 nginx]# echo "docker volume" > index.html
root@0a62e4026a15:/# curl 127.0.0.1
docker volume
root@0a62e4026a15:/#
root@0a62e4026a15:/#
root@0a62e4026a15:/# cd /usr/share/nginx/html/
root@0a62e4026a15:/usr/share/nginx/html# ls
index.html
root@0a62e4026a15:/usr/share/nginx/html# cat index.html
docker volume
root@0a62e4026a15:/usr/share/nginx/html#

为了保证Dockerfile可移植,构建镜像不能使用bind mount,很简单,就是外部管理,而不是docker自己管理

3.2、tmpfs mounts

docker run -itd --name tmptest --tmpfs /app nginx:latest
或者
docker run -itd --name tmptest --mount type=tmpfs,destination=/app nginx:latest

[root@node1 ~]# docker run -itd --name tmptest --tmpfs /app nginx:latest
12ae398d6eb6392d33dfc08d56137f29c2f28b994605123adfae311dfb25231f
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS        PORTS     NAMES
12ae398d6eb6   nginx:latest   "/docker-entrypoint.…"   2 seconds ago   Up 1 second   80/tcp    tmptest
[root@node1 ~]# docker exec -it 12ae398d6eb6 /bin/bash
root@12ae398d6eb6:/# ls
app  bin  boot    dev  docker-entrypoint.d  docker-entrypoint.sh    etc  home  lib    lib64  media  mnt  opt    proc  root  run  sbin  srv  sys  tmp  usr  var
root@12ae398d6eb6:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay          40G  3.5G   34G  10% /
tmpfs            64M     0   64M   0% /dev
tmpfs           1.8G     0  1.8G   0% /sys/fs/cgroup
shm              64M     0   64M   0% /dev/shm
tmpfs           1.8G     0  1.8G   0% /app
/dev/vda1        40G  3.5G   34G  10% /etc/hosts
tmpfs           1.8G     0  1.8G   0% /proc/acpi
tmpfs           1.8G     0  1.8G   0% /proc/scsi
tmpfs           1.8G     0  1.8G   0% /sys/firmware
root@12ae398d6eb6:/# cd app/
root@12ae398d6eb6:/app# ls
root@12ae398d6eb6:/app# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay          40G  3.5G   34G  10% /
tmpfs            64M     0   64M   0% /dev
tmpfs           1.8G     0  1.8G   0% /sys/fs/cgroup
shm              64M     0   64M   0% /dev/shm
tmpfs           1.8G     0  1.8G   0% /app
/dev/vda1        40G  3.5G   34G  10% /etc/hosts
tmpfs           1.8G     0  1.8G   0% /proc/acpi
tmpfs           1.8G     0  1.8G   0% /proc/scsi
tmpfs           1.8G     0  1.8G   0% /sys/firmware
root@12ae398d6eb6:/app# dd if=/dev/zero of=./test.txt count=2048 bs=1M
dd: error writing './test.txt': No space left on device
1824+0 records in
1823+0 records out
1911582720 bytes (1.9 GB, 1.8 GiB) copied, 0.904957 s, 2.1 GB/s

发现使用tmpfs 写的速率能达到 2.1 GB/s

[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS     NAMES
12ae398d6eb6   nginx:latest   "/docker-entrypoint.…"   57 seconds ago   Up 56 seconds   80/tcp    tmptest
[root@node1 ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    605c77e624dd   17 months ago   141MB
[root@node1 ~]# docker run -itd nginx
0ca7f5aa086815a9891f23e8ecca47783f1e2dbcd0d4e5c99e170f577c609cdc
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED              STATUS              PORTS     NAMES
0ca7f5aa0868   nginx          "/docker-entrypoint.…"   4 seconds ago        Up 2 seconds        80/tcp    gracious_rosalind
12ae398d6eb6   nginx:latest   "/docker-entrypoint.…"   About a minute ago   Up About a minute   80/tcp    tmptest
[root@node1 ~]# docker exec -it 0ca7f5aa0868
"docker exec" requires at least 2 arguments.
See 'docker exec --help'.

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Execute a command in a running container
[root@node1 ~]# docker exec -it 0ca7f5aa0868 /bin/bash
root@0ca7f5aa0868:/# dd if=/dev/zero of=./test.txt count=2048 bs=1M
^C690+0 records in
690+0 records out
723517440 bytes (724 MB, 690 MiB) copied, 2.0691 s, 350 MB/s

发现普通的磁盘写的速率能达到 350 MB/s

tmpfs会映射到宿主机的内存中,所以块,但是同样不稳定

3.3、volumns

1、走默认docker volume的创建
[root@node1 ~]# docker run -itd --name nginx_node -v /usr/share/nginx/html nginx
4191c61a053fcacc5e661e3b663227814503eb6e571275659da724186e4a44a2
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS        PORTS     NAMES
4191c61a053f   nginx     "/docker-entrypoint.…"   2 seconds ago   Up 1 second   80/tcp    nginx_node
[root@node1 ~]# docker volume ls
DRIVER    VOLUME NAME
local     e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8
local     wordpress_db_data
local     wordpress_wp_data

发现自动创建了一个volume e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8
[root@node1 ~]# docker volume inspect e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8
[
    {
        "CreatedAt": "2023-06-06T17:28:36+08:00",
        "Driver": "local",
        "Labels": {
            "com.docker.volume.anonymous": ""
        },
        "Mountpoint": "/var/lib/docker/volumes/e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8/_data",
        "Name": "e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8",
        "Options": null,
        "Scope": "local"
    }

修改docker管理的volume文件
[root@node1 _data]# vim index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!,journey</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>
[root@node1 _data]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED          STATUS          PORTS     NAMES
4191c61a053f   nginx     "/docker-entrypoint.…"   38 minutes ago   Up 38 minutes   80/tcp    nginx_node
[root@node1 _data]# docker exec -it 4191c61a053f /bin/bash
root@4191c61a053f:/# curl 127.0.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!,journey</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>

2、自己创建一个volume
[root@node1 _data]# docker volume ls
DRIVER    VOLUME NAME
local     e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8
local     wordpress_db_data
local     wordpress_wp_data
[root@node1 _data]# docker volume create journey_volume
journey_volume
[root@node1 _data]# docker volume ls
DRIVER    VOLUME NAME
local     e2117fbeda605fed2a98e06185ecaeb06104c63a84616d8267fc94a3a324b1e8
local     journey_volume
local     wordpress_db_data
local     wordpress_wp_data
[root@node1 _data]# docker volume inspect journey_volume
[
    {
        "CreatedAt": "2023-06-06T18:14:29+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/journey_volume/_data",
        "Name": "journey_volume",
        "Options": null,
        "Scope": "local"
    }
]
[root@node1 _data]# cd /var/lib/docker/volumes/journey_volume/_data
[root@node1 _data]# ls
[root@node1 _data]# cat > index.html
hello journey
^C
[root@node1 _data]# cat index.html
hello journey
[root@node1 _data]# docker run -itd --name nginx_journey_volume -p 8080:80 -v journey_volume:/usr/share/nginx/html nginx
49a95de0de50bd4ab00c6005a9d27053e02aef51487fe2bb7dcf34f9796488c5
[root@node1 _data]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS         PORTS                                   NAMES
49a95de0de50   nginx     "/docker-entrypoint.…"   8 seconds ago   Up 7 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   nginx_journey_volume
[root@node1 _data]# docker exec -it 49a95de0de50 /bin/bash
root@49a95de0de50:/#
exit
[root@node1 _data]# curl 127.0.0.1:8080
hello journey

建议docker的数据持久化采用volume方式

4、存储卷管理命令

1、新建volume
[root@node1 _data]# docker volume create journey_volume
journey_volume

2、查看volume列表
[root@node1 _data]# docker volume ls
DRIVER    VOLUME NAME
local     journey_volume

3、查看volume详细信息
[root@node1 _data]# docker volume inspect journey_volume
[
    {
        "CreatedAt": "2023-06-06T18:22:15+08:00",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/journey_volume/_data",
        "Name": "journey_volume",
        "Options": null,
        "Scope": "local"
    }
]

4、删除volume
[root@node1 _data]# docker volume rm journey_volume
journey_volume

5、容器使用volume
[root@node1 _data]# docker run -itd --name nginx_journey_volume -p 8080:80 -v journey_volume:/usr/share/nginx/html nginx

6、删除所有正在运行的容器
docker rm -f $(docker ps -a -q)

6、Dockerfile

1、描述

Dockerfile 是一个用来构建镜像的文本文件,文本内容包含了一条条构建镜像所需的指令和说明

2、Dockerfile语法

1、FROM

指定base镜像

# 制作基准镜像
FROM 镜像
# 比如我们要发布一个应用到tomcat里,那么的第一步就是FROM tomcat
FROM tomcat<:tags>

2、LABEL&MAINTAINER

指定维护者的信息

# MAINTAINER,一般写个人id或组织id
# LABEL 就是注释,方便阅读的,纯注释说明。不会对Dockerfile造成任何影响
# 比如:
MAINTAINER journey
LABEL version = "1.0.0"
LABEL description = "这是我们第一个版本"
# ...等等描述性信息,纯注释

3、WORKDIR

类似于Linux中的cd命令,但是他比cd高级的地方在于,我先cd,发现没有这个目录,我就自动创建出来,然后在cd进去,为后续的RUN 、 CMD 、 ENTRYPOINT指令配置工作目录

WORKDIR /usr/local/mydir

4、COPY

将文件从本地复制到镜像

# 示例
# 将1.txt拷贝到根目录下。它不仅仅能拷贝单个文件,还支持通配符
COPY 1.txt /
# 拷贝所有 abc 开头的文件到mydir目录下
COPY abc* /mydir/
# ? 是单个字符的占位符,比如匹配文件 abc1.log
COPY abc?.log /mydir/

5、ADD

将文件从本地复制到镜像。可以是Dockerfile所在的目录的一个相对路径;可以是URL,也可以是tar.gz(自动解压),由此可见要不COPY命令高级

# 示例
# 将1.txt拷贝到根目录的abc目录下。若/abc不存在,则会自动创建
ADD 1.txt /abc
# 将test.tar.gz解压缩然后将解压缩的内容拷贝到/opt/test
ADD test.tar.gz /opt/test

docker官方建议当要从远程复制文件时,尽量用curl/wget命令来代替ADD。因为用ADD的时候会创建更多的镜像层。镜像层的size也大

6、ADD

  • COPY能干的事ADD都能干,甚至还有附加功能
  • ADD可以支持拷贝的时候顺带解压缩文件,以及添加远程文件(不在本宿主机上的文件)类似wget
  • 只是文件拷贝的话可以用COPY,有额外操作只能用ADD代替

7、ENV

设置环境变量,环境变量可被后面的指令使用。例如 :

# 设置环境常量,方便下文引用,比如:
ENV JAVA_HOME /usr/local/jdk1.8
# 引用上面的常量,下面的RUN指令可以先不管啥意思,目的是想说明下文可以通过${xxx}的方式引用
RUN ${JAVA_HOME}/bin/java -jar xxx.jar

8、ENV

创建一个可以从本地主机或其他容器挂载的挂载点,一般用来存放数据库和需要保持的数据等

VOLUME ["/data"]

示例 :

[root@node1 test6]# cat Dockerfile
FROM centos
RUN mkdir /myvol
RUN echo "hello world" > /myvol/greeting
VOLUME /myvol
[root@node1 test6]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/nginx   v1        24bc0c4e811a   2 hours ago     231MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 test6]# docker build -t bjbfd/myvol:v1 .
[+] Building 15.2s (7/7) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                   0.0s
 => => transferring dockerfile: 121B                                                                                                                                                                   0.0s
 => [internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [internal] load metadata for docker.io/library/centos:latest                                                                                                                                      15.2s
 => [1/3] FROM docker.io/library/centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177                                                                                        0.0s
 => CACHED [2/3] RUN mkdir /myvol                                                                                                                                                                      0.0s
 => CACHED [3/3] RUN echo "hello world" > /myvol/greeting                                                                                                                                              0.0s
 => exporting to image                                                                                                                                                                                 0.0s
 => => exporting layers                                                                                                                                                                                0.0s
 => => writing image sha256:24bc0c4e811a1fdd397551a2b4357c2b31da177feb0e815de8e1d222e4eaba15                                                                                                           0.0s
 => => naming to docker.io/bjbfd/myvol:v1                                                                                                                                                              0.0s
[root@node1 test6]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/myvol   v1        24bc0c4e811a   2 hours ago     231MB
bjbfd/nginx   v1        24bc0c4e811a   2 hours ago     231MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 test6]# docker run -itd bjbfd/myvol:v1
bdd1b97721308216d1739a5e4d0e3340f108032b99d4ef1193432a89ad4f45e5
[root@node1 test6]# docker ps -a
CONTAINER ID   IMAGE            COMMAND       CREATED          STATUS          PORTS     NAMES
bdd1b9772130   bjbfd/myvol:v1   "/bin/bash"   13 seconds ago   Up 12 seconds             admiring_colden
[root@node1 test6]# docker inspect bdd1b9772130
......
......
"Mounts": [
    {
        "Type": "volume",
        "Name": "5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73",
        "Source": "/var/lib/docker/volumes/5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73/_data",
        "Destination": "/myvol",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]
......
......

[root@node1 test6]# docker volume ls
DRIVER    VOLUME NAME
local     5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73
[root@node1 test6]# docker inspect 5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73
[
    {
        "CreatedAt": "2023-06-07T21:31:45+08:00",
        "Driver": "local",
        "Labels": {
            "com.docker.volume.anonymous": ""
        },
        "Mountpoint": "/var/lib/docker/volumes/5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73/_data",
        "Name": "5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73",
        "Options": null,
        "Scope": "local"
    }
]
[root@node1 test6]# docker ps -a
CONTAINER ID   IMAGE            COMMAND       CREATED         STATUS         PORTS     NAMES
bdd1b9772130   bjbfd/myvol:v1   "/bin/bash"   4 minutes ago   Up 4 minutes             admiring_colden
[root@node1 test6]# docker rm -f bdd1b9772130
bdd1b9772130
[root@node1 test6]# docker volume ls
DRIVER    VOLUME NAME
local     5bff6f181a52cd554ef97eac63e06cfcb6242be321f03b9bcc9f58cfbfd82e73

总结 : 其实就是发现是一个挂载docker容器管理的一个volume。删除容器,volume不删除

3、运行指令

一共有三个:RUN、CMD、ENTRYPOINT

1、运行指令

构建镜像时执行的命令

  • 执行时机
    RUN指令是在构建镜像时运行,在构建时能修改镜像内部的文件。每条指令将在当前镜像基础上执行,并提交为新的镜像
  • 命令格式
    命令格式不光是RUN独有,而是下面的CMD和ENTRYPOINT都通用

SHELL命令格式 :

RUN yum -y install vim

EXEC命令格式 :

RUN ["yum","-y","install","vim"]

区别 :

  • SHELL:当前shell是父进程,生成一个子shell进程去执行脚本,脚本执行完后退出子shell进程,回到当前父shell进程
  • EXEC:用EXEC进程替换当前进程,并且保持PID不变,执行完毕后直接退出,不会退回原来的进程

总结 : 也就是说shell会创建子进程执行,EXEC不会创建子进程

2、CMD

  • 执行时机
    容器启动时执行,而不是镜像构建时执行
  • 解释说明
    容器启动时运行指定的命令

Dockerfile 中可以有多个 CMD 指令,但只有最后一个生效。重点在于如果容器启动的时候有其他额外的附加指令,则CMD指令不生效

3、CMD

  • 执行时机
    器创建时执行,而不是镜像构建时执行
  • 解释说明
    在容器启动的时候执行此命令,且Dockerfile中只有最后一个ENTRYPOINT会被执行,推荐用EXEC格式

比如 :

ENTRYPOINT ["ps","-ef"]

4、RUN vs CMD vs ENTRYPOINT

简单说 :
1、RUN 执行命令并创建新的镜像层,RUN 经常用于安装软件包
2、CMD设置容器启动后默认执行的命令及其参数,但CMD能够被 docker run 后面跟的命令行参数替换
3、ENTRYPOINT配置容器启动时运行的命令

示例 :

[root@node1 test2]# cat Dockerfile
FROM centos
RUN ["echo", "build image"]
CMD ["echo", "start container"]
[root@node1 test2]# ls
Dockerfile
[root@node1 test2]# docker build -t bjbfd/run_cmd:v1 .
[+] Building 15.4s (6/6) FINISHED
 => [internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [internal] load build definition from Dockerfile                                                                                                                                                   0.0s
 => => transferring dockerfile: 109B                                                                                                                                                                   0.0s
 => [internal] load metadata for docker.io/library/centos:latest                                                                                                                                      15.2s
 => CACHED [1/2] FROM docker.io/library/centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177                                                                                 0.0s
 => [2/2] RUN ["echo", "build image"]                                                                                                                                                                  0.2s
 => exporting to image                                                                                                                                                                                 0.0s
 => => exporting layers                                                                                                                                                                                0.0s
 => => writing image sha256:dd8e041707d9863f19fcfde891232638f89bd5cc78dab7591a468ffe6bd0ad05                                                                                                           0.0s
 => => naming to docker.io/bjbfd/run_cmd:v1                                                                                                                                                            0.0s
[root@node1 test2]# docker images
REPOSITORY      TAG       IMAGE ID       CREATED         SIZE
bjbfd/run_cmd   v1        dd8e041707d9   3 minutes ago   231MB
nginx           latest    605c77e624dd   17 months ago   141MB
[root@node1 test2]# docker run -it bjbfd/run_cmd:v1
start container

总结: run是构建镜像时候的指令,CMD和ENTRYPOINT是启动容器时的指令

5、CMD VS ENTRYPOINT案例

[root@node1 test3]# cat Dockerfile
FROM centos
RUN ["echo", "image build"]
ENTRYPOINT ["ps"]
CMD ["-ef"]
[root@node1 test3]# vim Dockerfile
[root@node1 test3]#
[root@node1 test3]#
[root@node1 test3]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@node1 test3]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    605c77e624dd   17 months ago   141MB
[root@node1 test3]# ll
总用量 4
-rw-r--r-- 1 root root 70 6月   7 22:17 Dockerfile
[root@node1 test3]# ll
总用量 4
-rw-r--r-- 1 root root 70 6月   7 22:17 Dockerfile
[root@node1 test3]# docker build -t bjbfd/cmd_entrypoint:v1 .
[+] Building 15.2s (6/6) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                   0.0s
 => => transferring dockerfile: 107B                                                                                                                                                                   0.0s
 => [internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [internal] load metadata for docker.io/library/centos:latest                                                                                                                                      15.2s
 => [1/2] FROM docker.io/library/centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177                                                                                        0.0s
 => CACHED [2/2] RUN ["echo", "build image"]                                                                                                                                                           0.0s
 => exporting to image                                                                                                                                                                                 0.0s
 => => exporting layers                                                                                                                                                                                0.0s
 => => writing image sha256:945f13a63927b4019b3785c6ab6d3479e2ea100cb9351d2663cb33df6d02f175                                                                                                           0.0s
 => => naming to docker.io/bjbfd/cmd_entrypoint:v1                                                                                                                                                     0.0s
[root@node1 test3]# docker images
REPOSITORY             TAG       IMAGE ID       CREATED         SIZE
bjbfd/cmd_entrypoint   v1        945f13a63927   8 minutes ago   231MB
nginx                  latest    605c77e624dd   17 months ago   141MB
[root@node1 test3]# docker run -it bjbfd/cmd_entrypoint:v1
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 14:19 pts/0    00:00:00 ps -ef
[root@node1 test3]# docker run -it bjbfd/cmd_entrypoint:v1 -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  47572  1784 pts/0    Rs+  14:19   0:00 ps -aux

总结 : 从这个示例中就可以看出区别,ENTRYPOINT无论容器启动是否带参数,都会执行。而CMD就不一样。上面没带参数那么它就会被执行。而下面带了-aux,CMD指令就不会执行了

4、查看镜像history

docker history 605c77e624dd --no-trunc
注意 : --no-trunc 其实就是不进行缩写展示,都展示出来。通过该命令可以看到镜像的构建过程

IMAGE                                                                     CREATED         CREATED BY                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 SIZE      COMMENT
sha256:605c77e624ddb75e6110f997c58876baa13f8754486b461117934b24a9dc3a85   17 months ago   /bin/sh -c #(nop)  CMD ["nginx" "-g" "daemon off;"]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  STOPSIGNAL SIGQUIT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  EXPOSE 80                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  ENTRYPOINT ["/docker-entrypoint.sh"]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop) COPY file:09a214a3e07c919af2fb2d7c749ccbc446b8c10eb217366e5a65640ee9edcc25 in /docker-entrypoint.d                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       4.61kB    
<missing>                                                                 17 months ago   /bin/sh -c #(nop) COPY file:0fd5fca330dcd6a7de297435e32af634f29f7132ed0550d342cad9fd20158258 in /docker-entrypoint.d                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1.04kB    
<missing>                                                                 17 months ago   /bin/sh -c #(nop) COPY file:0b866ff3fc1ef5b03c4e6c8c513ae014f691fb05d530257dfffd07035c1b75da in /docker-entrypoint.d                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1.96kB    
<missing>                                                                 17 months ago   /bin/sh -c #(nop) COPY file:65504f71f5855ca017fb64d502ce873a31b2e0decd75297a8fb0a287f97acf92 in /                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          1.2kB     
<missing>                                                                 17 months ago   /bin/sh -c set -x     && addgroup --system --gid 101 nginx     && adduser --system --disabled-login --ingroup nginx --no-create-home --home /nonexistent --gecos "nginx user" --shell /bin/false --uid 101 nginx     && apt-get update     && apt-get install --no-install-recommends --no-install-suggests -y gnupg1 ca-certificates     &&     NGINX_GPGKEY=573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62;     found='';     for server in         hkp://keyserver.ubuntu.com:80         pgp.mit.edu     ; do         echo "Fetching GPG key $NGINX_GPGKEY from $server";         apt-key adv --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$NGINX_GPGKEY" && found=yes && break;     done;     test -z "$found" && echo >&2 "error: failed to fetch GPG key $NGINX_GPGKEY" && exit 1;     apt-get remove --purge --auto-remove -y gnupg1 && rm -rf /var/lib/apt/lists/*     && dpkgArch="$(dpkg --print-architecture)"     && nginxPackages="         nginx=${NGINX_VERSION}-${PKG_RELEASE}         nginx-module-xslt=${NGINX_VERSION}-${PKG_RELEASE}         nginx-module-geoip=${NGINX_VERSION}-${PKG_RELEASE}         nginx-module-image-filter=${NGINX_VERSION}-${PKG_RELEASE}         nginx-module-njs=${NGINX_VERSION}+${NJS_VERSION}-${PKG_RELEASE}     "     && case "$dpkgArch" in         amd64|arm64)             echo "deb https://nginx.org/packages/mainline/debian/ bullseye nginx" >> /etc/apt/sources.list.d/nginx.list             && apt-get update             ;;         *)             echo "deb-src https://nginx.org/packages/mainline/debian/ bullseye nginx" >> /etc/apt/sources.list.d/nginx.list                         && tempDir="$(mktemp -d)"             && chmod 777 "$tempDir"                         && savedAptMark="$(apt-mark showmanual)"                         && apt-get update             && apt-get build-dep -y $nginxPackages             && (                 cd "$tempDir"                 && DEB_BUILD_OPTIONS="nocheck parallel=$(nproc)"                     apt-get source --compile $nginxPackages             )                         && apt-mark showmanual | xargs apt-mark auto > /dev/null             && { [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark; }                         && ls -lAFh "$tempDir"             && ( cd "$tempDir" && dpkg-scanpackages . > Packages )             && grep '^Package: ' "$tempDir/Packages"             && echo "deb [ trusted=yes ] file://$tempDir ./" > /etc/apt/sources.list.d/temp.list             && apt-get -o Acquire::GzipIndexes=false update             ;;     esac         && apt-get install --no-install-recommends --no-install-suggests -y                         $nginxPackages                         gettext-base                         curl     && apt-get remove --purge --auto-remove -y && rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/nginx.list         && if [ -n "$tempDir" ]; then         apt-get purge -y --auto-remove         && rm -rf "$tempDir" /etc/apt/sources.list.d/temp.list;     fi     && ln -sf /dev/stdout /var/log/nginx/access.log     && ln -sf /dev/stderr /var/log/nginx/error.log     && mkdir /docker-entrypoint.d   61.1MB    
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  ENV PKG_RELEASE=1~bullseye                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  ENV NJS_VERSION=0.7.1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  ENV NGINX_VERSION=1.21.5                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  LABEL maintainer=NGINX Docker Maintainers <docker-maint@nginx.com>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop)  CMD ["bash"]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            0B        
<missing>                                                                 17 months ago   /bin/sh -c #(nop) ADD file:09675d11695f65c55efdc393ff0cd32f30194cd7d0fbef4631eebfed4414ac97 in /                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           80.4MB    

5、小案例

[root@node1 test7]# cat Demo.java
public class Demo {

    public static void main(String[] args) {
        System.out.println("hello Dockerfile.");
    }
}
[root@node1 test7]# cat Dockerfile
FROM openjdk:8
ADD ./Demo.java /opt
WORKDIR /opt
RUN javac Demo.java
CMD ["java", "Demo"]
[root@node1 test7]# docker build -t bjbfd/hello:v1 .
[+] Building 15.2s (9/9) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                   0.0s
 => => transferring dockerfile: 128B                                                                                                                                                                   0.0s
 => [internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [internal] load metadata for docker.io/library/openjdk:8                                                                                                                                          15.2s
 => [internal] load build context                                                                                                                                                                      0.0s
 => => transferring context: 30B                                                                                                                                                                       0.0s
 => [1/4] FROM docker.io/library/openjdk:8@sha256:8a9d5c43f540e8d0c003c723a2c8bd20ae350a2efed6fb5719cae33b026f8e7c                                                                                     0.0s
 => CACHED [2/4] ADD ./Demo.java /opt                                                                                                                                                                  0.0s
 => CACHED [3/4] WORKDIR /opt                                                                                                                                                                          0.0s
 => CACHED [4/4] RUN javac Demo.java                                                                                                                                                                   0.0s
 => exporting to image                                                                                                                                                                                 0.0s
 => => exporting layers                                                                                                                                                                                0.0s
 => => writing image sha256:ef457d1321f992322895d07aa6b72df73e4252882b0a12c0cd2ed9e4076f816c                                                                                                           0.0s
 => => naming to docker.io/bjbfd/hello:v1                                                                                                                                                              0.0s
[root@node1 test7]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/hello   v1        ef457d1321f9   3 minutes ago   526MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 test7]# docker run -it bjbfd/hello:v1
hello Dockerfile.
[root@node1 test7]# docker tag bjbfd/hello:v1 bjbfd/hello:v2
[root@node1 test7]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
bjbfd/hello   v1        ef457d1321f9   4 minutes ago   526MB
bjbfd/hello   v2        ef457d1321f9   4 minutes ago   526MB
nginx         latest    605c77e624dd   17 months ago   141MB
[root@node1 test7]# docker push bjbfd/hello:v2
The push refers to repository [docker.io/bjbfd/hello]
29fd394f129a: Pushed
5f70bf18a086: Mounted from bjbfd/stress
231634b0742f: Pushed
bff9fe6e429c: Mounted from library/openjdk
7c245b2fe4f1: Mounted from library/openjdk
f9e18e59a565: Mounted from library/openjdk
26a504e63be4: Mounted from library/openjdk
8bf42db0de72: Mounted from library/openjdk
31892cc314cb: Mounted from library/openjdk
11936051f93b: Mounted from library/openjdk
v2: digest: sha256:820a2bc79d5273163266326bb9be8d12f9ffe55b95e997ebd309e319e6ebd4df size: 2415

image.png

7、Docker Compose

1、Docker Compose wordpress例子

[root@node1 wordpress]# cat docker-compose.yml
services:
  db:
    # We use a mariadb image which supports both amd64 & arm64 architecture
    image: mariadb:10.6.4-focal
    # If you really want to use MySQL, uncomment the following line
    #image: mysql:8.0.27
    command: '--default-authentication-plugin=mysql_native_password'
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=somewordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
    expose:
      - 3306
      - 33060
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    volumes:
      - wp_data:/var/www/html
    ports:
      - 80:80
    restart: always
    environment:
      - WORDPRESS_DB_HOST=db
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
      - WORDPRESS_DB_NAME=wordpress
volumes:
  db_data:
  wp_data:

2、Docker服务编排

image.png

注意 : 上面的wordpress其实就是依赖db,所有有启动顺序

3、Docker服务编排工具

1、Docker Compose

Compose是用于定义和运行多容器Docker应用程序的工具。通过Compose,可以使用YML文件来配置应用程序需要的所有服务。然后,使用一个命令,就可以用YML文件配置中创建并启动所有服务

2、Docker Stack

  • stack 命令不支持build,compose 不支持deploy
  • stack 是go语言内置命令,compose是python第三方工具(之前的版本,现在直接集成,在安装docker的时候)
  • stack 是swarm mode的一部分

4、YML说明

4.1、version

compose 文件格式有3个版本,分别为1、2.x和3.x。目前主流为3.x,其支持docker 1.13.0及其以上的版本

4.2、service

定义所有的service信息,services下面第一级别的key就是service的名称

4.3、build

指定Dockerfile所在的文件夹的路径。Compose将会利用他自动构建这个镜像,然后使用这个镜像

示例 :

[root@node1 nginx]# ls
docker-compose.yml  Dockerfile
[root@node1 nginx]# cat docker-compose.yml
version: "3.9"
services:
  nginx_compose:
    build:
      context: .
      dockerfile: Dockerfile
    image: bjbfd/nginx_compose
    container_name: nginx_compose
[root@node1 nginx]# ls
docker-compose.yml  Dockerfile
[root@node1 nginx]# docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
[root@node1 nginx]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@node1 nginx]# ll
总用量 8
-rw-r--r-- 1 root root 166 6月   8 14:40 docker-compose.yml
-rw-r--r-- 1 root root  96 5月  27 11:20 Dockerfile
[root@node1 nginx]# cat docker-compose.yml
version: "3.9"
services:
  nginx_compose:
    build:
      context: .
      dockerfile: Dockerfile
    image: bjbfd/nginx_compose
    container_name: nginx_compose
[root@node1 nginx]# cat Dockerfile
FROM nginx
RUN echo '这是一个本地构建的nginx镜像' > /usr/share/nginx/html/index.html
[root@node1 nginx]# docker compose up -d
[+] Running 1/1
 ! nginx_compose Warning                                                                                                                                                                              33.3s
[+] Building 49.3s (6/7)
[+] Building 49.3s (7/7) FINISHED
 => [nginx_compose internal] load build definition from Dockerfile                                                                                                                                     0.0s
 => => transferring dockerfile: 133B                                                                                                                                                                   0.0s
 => [nginx_compose internal] load .dockerignore                                                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [nginx_compose internal] load metadata for docker.io/library/nginx:latest                                                                                                                         49.2s
 => [nginx_compose auth] library/nginx:pull token for registry-1.docker.io                                                                                                                             0.0s
 => [nginx_compose 1/2] FROM docker.io/library/nginx@sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31                                                                           0.0s
 => => resolve docker.io/library/nginx@sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31                                                                                         0.0s  => CACHED [nginx_compose 2/2] RUN echo '这是一个本地构建的nginx镜像' > /usr/share/nginx/html/index.html                                                                                                          0.0s_compose] exporting to image                                                                                                                                                                 0.0s
 => [nginx_compose] exporting to image                                                                                                                                                                 0.0s
 => => exporting layers                                                                                                                                                                                0.0s
 => => writing image sha256:faa8eb07eb08d062b33b637b0ed6d4b384a341019553c37aeb9f5040c8fcda1e                                                                                                           0.0s
 => => naming to docker.io/bjbfd/nginx_compose                                                                                                                                                         0.0s
[+] Running 2/2
 ✔ Network nginx_default    Created                                                                                                                                                                    0.0s
 ✔ Container nginx_compose  Started                                                                                                                                                                    0.3s
[root@node1 nginx]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED       SIZE
bjbfd/nginx_compose   latest    faa8eb07eb08   12 days ago   141MB
[root@node1 nginx]# docker ps -a
CONTAINER ID   IMAGE                 COMMAND                   CREATED          STATUS          PORTS     NAMES
6036109c9eb8   bjbfd/nginx_compose   "/docker-entrypoint.…"   17 seconds ago   Up 15 seconds   80/tcp    nginx_compose
[root@node1 nginx]# docker exec -it 6036109c9eb8 /bin/bash
root@6036109c9eb8:/# curl 127.0.0.1
这是一个本地构建的nginx镜像

4.4、image

指定服务所使用的镜像

[root@node1 image]# cat docker-compose.yml
version: "3.9"
services:
  nginx_image:
    image: nginx:latest
    container_name: nginx_image
    ports:
     - "8080:80"
[root@node1 image]# docker compose up -d
[+] Running 7/7
 ✔ nginx_image 6 layers [⣿⣿⣿⣿⣿⣿]      0B/0B      Pulled                                                                                                  15.7s
   ✔ a2abf6c4d29d Already exists                                                                                                                          0.0s
   ✔ a9edb18cadd1 Already exists                                                                                                                          0.0s
   ✔ 589b7251471a Already exists                                                                                                                          0.0s
   ✔ 186b1aaa4aa6 Already exists                                                                                                                          0.0s
   ✔ b4df32aa5a72 Already exists                                                                                                                          0.0s
   ✔ a0bcbecc962e Already exists                                                                                                                          0.0s
[+] Building 0.0s (0/0)
[+] Running 2/2
 ✔ Network image_default  Created                                                                                                                         0.0s
 ✔ Container nginx_image  Started                                                                                                                         0.3s
[root@node1 image]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                   NAMES
6563839cbfd9   nginx:latest   "/docker-entrypoint.…"   4 seconds ago   Up 3 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   nginx_image
[root@node1 image]# curl 127.0.0.1:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
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>

4.5、ports

定义宿主机端口和容器端口的映射,可以使用宿主机IP+宿主机端口进行访问 宿主机端口:容器端口

类似下面docker run语句 :
docker run -itd -p 8080:80 nginx

4.6、expose

定义容器用到的端口(一般用来标识镜像使用的端口,方便用ports映射)暴露端口,与ports不同的是expose只可以暴露端口而不能映射到主机,只供外部服务(其他容器)连接使用;近可以指定内部端口为参数

version: "3.9"
services: 
  nginx_image:
    image: nginx:latest 
    container_name: nginx_image
    expose:
     - "80"
     - "3000"

4.7、volumes

卷挂载路径,定义宿主机的目录/文件和容器的目录文件的映射 宿主机路径:容器路径

4.8、depends_on

规定service加载顺序,例如数据库服务需要在后台服务前运行

4.9、restart

配置重启,docker每次启动会启动该服务

4.10、networks

容器使用的网络命名空间

networks:
  default:
    external:
      name:mynet

功能同下面docker run :

docker run -itd --network mynet nginx

4.11、environment

设置环境变量。可以属于数组或字典两种格式。如果只给定变量的名称则会自动加载它在Compose主机上的值,可以用来防止泄密不必须要的数据

4.12、commnad

覆盖容器启动后默认执行的名,支持shell格式和[]格式

[root@node1 command]# cat docker-compose.yml
version: "3.9"
services:
  nginx_image:
    image: nginx:latest
    container_name: nginx_container
    command : /bin/bash -c "while true;do echo test;sleep 1;done"
[root@node1 command]# docker compose up -d
[+] Building 0.0s (0/0)
[+] Running 2/2
 ✔ Network command_default    Created                                                                                                                                                                  0.0s
 ✔ Container nginx_container  Started
[root@node1 command]# docker logs -f 7d64038e8b83
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test

4.13、container_name

指定容器的名称(等同于 docker run --name的作用)

4.14、healthcheck

定义容器健康状态检查

[root@node1 healthchck]# cat docker-compose.yml
version: "3.9"

services:
  nginx_image:
    image: nginx:latest
    container_name: nginx_container
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 5s
      timeout: 10s
      retries: 3
[root@node1 healthchck]# docker compose up -d
[+] Building 0.0s (0/0)
[+] Running 2/2
 ✔ Network healthchck_default  Created                                                                                                                    0.0s
 ✔ Container nginx_container   Started                                                                                                                    0.3s
[root@node1 healthchck]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS                    PORTS     NAMES
a26dfce47865   nginx:latest   "/docker-entrypoint.…"   12 seconds ago   Up 11 seconds (healthy)   80/tcp    nginx_container
[root@node1 healthchck]# docker logs a26dfce47865
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/06/08 08:05:45 [notice] 1#1: using the "epoll" event method
2023/06/08 08:05:45 [notice] 1#1: nginx/1.21.5
2023/06/08 08:05:45 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2023/06/08 08:05:45 [notice] 1#1: OS: Linux 3.10.0-1127.19.1.el7.x86_64
2023/06/08 08:05:45 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/06/08 08:05:45 [notice] 1#1: start worker processes
2023/06/08 08:05:45 [notice] 1#1: start worker process 30
2023/06/08 08:05:45 [notice] 1#1: start worker process 31
127.0.0.1 - - [08/Jun/2023:08:05:50 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.74.0" "-"
127.0.0.1 - - [08/Jun/2023:08:05:55 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.74.0" "-"
127.0.0.1 - - [08/Jun/2023:08:06:00 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.74.0" "-"

4.15、extends

这个标签可以扩展另一个服务,扩展内容可以是来自当前文件,也可以是来自其他文件,相同服务的情况下,后来者会有选择地覆盖原有配置

webapp:
  image: nginx
  environment:
    - DEBUG=false
    - SEND_EMAILS=false


web:
  extends:
    file: common.yml
    service: webapp
  ports:
    - "8080:8000"
  links:
    - db
  environment:
    - DEBUG=false
db:
  image: mysql 

5、docker compose常用命令

[root@node1 wordpress]# cat docker-compose.yml
services:
  db:
    # We use a mariadb image which supports both amd64 & arm64 architecture
    image: mariadb:10.6.4-focal
    # If you really want to use MySQL, uncomment the following line
    #image: mysql:8.0.27
    command: '--default-authentication-plugin=mysql_native_password'
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=somewordpress
      - MYSQL_DATABASE=wordpress
      - MYSQL_USER=wordpress
      - MYSQL_PASSWORD=wordpress
    expose:
      - 3306
      - 33060
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    volumes:
      - wp_data:/var/www/html
    ports:
      - 80:80
    restart: always
    environment:
      - WORDPRESS_DB_HOST=db
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
      - WORDPRESS_DB_NAME=wordpress
volumes:
  db_data:
  wp_data:

1、启动
[root@node1 wordpress]# docker compose up -d
[+] Running 33/33
 ✔ wordpress 21 layers [⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿]      0B/0B      Pulled                                                                                                                                 47.6s
   ✔ a2abf6c4d29d Already exists                                                                                                                                                                       0.0s
   ✔ c5608244554d Pull complete                                                                                                                                                                        0.3s
   ✔ 2d07066487a0 Pull complete                                                                                                                                                                       24.1s
   ✔ 1b6dfaf1958c Pull complete                                                                                                                                                                       24.2s
   ✔ 32c5e6a60073 Pull complete                                                                                                                                                                       25.3s
   ✔ 90cf855b27cc Pull complete                                                                                                                                                                       25.3s
   ✔ 8b0f1068c586 Pull complete                                                                                                                                                                       25.3s
   ✔ 5355461305e8 Pull complete                                                                                                                                                                       25.5s
   ✔ ad1eec592342 Pull complete                                                                                                                                                                       25.5s
   ✔ e03fbc76cb78 Pull complete                                                                                                                                                                       26.9s
   ✔ 1f5796e48b39 Pull complete                                                                                                                                                                       27.0s
   ✔ 72fbe8e1d4e7 Pull complete                                                                                                                                                                       27.0s
   ✔ 96edece66175 Pull complete                                                                                                                                                                       27.0s
   ✔ 5f46f0743de2 Pull complete                                                                                                                                                                       28.6s
   ✔ c9f9671a5e1f Pull complete                                                                                                                                                                       29.8s
   ✔ 3f543dcd35b1 Pull complete                                                                                                                                                                       29.8s
   ✔ c88e21a0c2a0 Pull complete                                                                                                                                                                       29.9s
   ✔ 964b4457a910 Pull complete                                                                                                                                                                       29.9s
   ✔ 0d55fb9a64ef Pull complete                                                                                                                                                                       31.9s
   ✔ fb009ff7c567 Pull complete                                                                                                                                                                       32.1s
   ✔ 4f058a67a50d Pull complete                                                                                                                                                                       32.1s
 ✔ db 10 layers [⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿]      0B/0B      Pulled                                                                                                                                                   47.6s
   ✔ 7b1a6ab2e44d Pull complete                                                                                                                                                                       19.6s
   ✔ 034655750c88 Pull complete                                                                                                                                                                       19.6s
   ✔ f0b757a2a0f0 Pull complete                                                                                                                                                                       20.2s
   ✔ 5c37daf8b6b5 Pull complete                                                                                                                                                                       20.5s
   ✔ b4cd9409b0f6 Pull complete                                                                                                                                                                       20.5s
   ✔ dbcda06785eb Pull complete                                                                                                                                                                       21.4s
   ✔ a34cd90f184c Pull complete                                                                                                                                                                       21.5s
   ✔ fd6cef4ce489 Pull complete                                                                                                                                                                       21.5s
   ✔ 3cb89a1550ea Pull complete                                                                                                                                                                       31.9s
   ✔ df9f153bd930 Pull complete                                                                                                                                                                       31.9s
[+] Building 0.0s (0/0)
[+] Running 3/3
 ✔ Network wordpress_default        Created                                                                                                                                                            0.0s
 ✔ Container wordpress-db-1         Started                                                                                                                                                            1.8s
 ✔ Container wordpress-wordpress-1  Started

2、查看运行的容器
[root@node1 wordpress]# docker compose ps -a
NAME                    IMAGE                  COMMAND                  SERVICE             CREATED             STATUS              PORTS
wordpress-db-1          mariadb:10.6.4-focal   "docker-entrypoint.s…"   db                  55 seconds ago      Up 53 seconds       3306/tcp, 33060/tcp
wordpress-wordpress-1   wordpress:latest       "docker-entrypoint.s…"   wordpress           54 seconds ago      Up 53 seconds       0.0.0.0:80->80/tcp, :::80->80/tcp

3、根据service查看日志
[root@node1 wordpress]# docker compose logs db
wordpress-db-1  | 2023-06-08 08:26:42+00:00 [Note] [Entrypoint]: Entrypoint script for MariaDB Server 1:10.6.4+maria~focal started.
wordpress-db-1  | 2023-06-08 08:26:43+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
wordpress-db-1  | 2023-06-08 08:26:43+00:00 [Note] [Entrypoint]: Entrypoint script for MariaDB Server 1:10.6.4+maria~focal started.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] mysqld (server 10.6.4-MariaDB-1:10.6.4+maria~focal) starting as process 1 ...
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Number of pools: 1
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Using crc32 + pclmulqdq instructions
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] mysqld: O_TMPFILE is not supported on /tmp (disabling future attempts)
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Using Linux native AIO
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Initializing buffer pool, total size = 134217728, chunk size = 134217728
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Completed initialization of buffer pool
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: 128 rollback segments are active.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Creating shared tablespace for temporary tables
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: 10.6.4 started; log sequence number 42347; transaction id 14
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] Plugin 'FEEDBACK' is disabled.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
wordpress-db-1  | 2023-06-08  8:26:43 0 [Warning] 'default-authentication-plugin' is MySQL 5.6 / 5.7 compatible option. To be implemented in later versions.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Warning] You need to use --log-bin to make --expire-logs-days or --binlog-expire-logs-seconds work.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] Server socket created on IP: '0.0.0.0'.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] Server socket created on IP: '::'.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] InnoDB: Buffer pool(s) load completed at 230608  8:26:43
wordpress-db-1  | 2023-06-08  8:26:43 0 [Warning] 'proxies_priv' entry '@% root@6df4335965a2' ignored in --skip-name-resolve mode.
wordpress-db-1  | 2023-06-08  8:26:43 0 [Note] mysqld: ready for connections.
wordpress-db-1  | Version: '10.6.4-MariaDB-1:10.6.4+maria~focal'  socket: '/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution
[root@node1 wordpress]# docker compose logs wordpress
wordpress-wordpress-1  | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.30.0.3. Set the 'ServerName' directive globally to suppress this message
wordpress-wordpress-1  | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.30.0.3. Set the 'ServerName' directive globally to suppress this message
wordpress-wordpress-1  | [Thu Jun 08 08:26:43.376584 2023] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.51 (Debian) PHP/7.4.27 configured -- resuming normal operations
wordpress-wordpress-1  | [Thu Jun 08 08:26:43.376655 2023] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'

4、查看镜像
[root@node1 wordpress]# docker compose images
CONTAINER               REPOSITORY          TAG                 IMAGE ID            SIZE
wordpress-db-1          mariadb             10.6.4-focal        12e05d5da3c5        409MB
wordpress-wordpress-1   wordpress           latest              c3c92cc3dcb1        616MB

5、登录容器
[root@node1 wordpress]# docker compose exec -it db /bin/bash

6、top查看运行的进程
[root@node1 wordpress]# docker compose top
wordpress-db-1
UID       PID     PPID    C    STIME   TTY   TIME       CMD
polkitd   10170   10150   0    16:26   ?     00:00:00   mysqld --default-authentication-plugin=mysql_native_password

wordpress-wordpress-1
UID    PID     PPID    C    STIME   TTY   TIME       CMD
root   10254   10232   0    16:26   ?     00:00:00   apache2 -DFOREGROUND
33     10330   10254   0    16:26   ?     00:00:00   apache2 -DFOREGROUND
33     10331   10254   0    16:26   ?     00:00:00   apache2 -DFOREGROUND
33     10332   10254   0    16:26   ?     00:00:00   apache2 -DFOREGROUND
33     10333   10254   0    16:26   ?     00:00:00   apache2 -DFOREGROUND
33     10334   10254   0    16:26   ?     00:00:00   apache2 -DFOREGROUND
33     10522   10254   0    16:30   ?     00:00:00   apache2 -DFOREGROUND

7、停止
[root@node1 wordpress]# docker compose ps
NAME                    IMAGE                  COMMAND                  SERVICE             CREATED             STATUS              PORTS
wordpress-db-1          mariadb:10.6.4-focal   "docker-entrypoint.s…"   db                  7 minutes ago       Up 7 minutes        3306/tcp, 33060/tcp
wordpress-wordpress-1   wordpress:latest       "docker-entrypoint.s…"   wordpress           7 minutes ago       Up 7 minutes        0.0.0.0:80->80/tcp, :::80->80/tcp
[root@node1 wordpress]# docker compose down
[+] Running 3/2
 ✔ Container wordpress-wordpress-1  Removed                                                                                                                                                            1.2s
 ✔ Container wordpress-db-1         Removed                                                                                                                                                            0.3s
 ✔ Network wordpress_default        Removed                                                                                                                                                            0.0s
[root@node1 wordpress]# docker compose ps
NAME                IMAGE               COMMAND             SERVICE             CREATED             STATUS              PORTS

6、实例

1、docker镜像启动nacos
docker pull nacos/nacos-server
docker run -itd -p 8080:8848 --env MODE=standalone --name nacos nacos/nacos-server 
http://ip:8080/nacos/

2、源码编译
安装JDK
yum install java-1.8.0-openjdk-devel.x86_64

安装maven
yum install -y maven

下载nacos
git clone https://gitee.com/mirrors/Nacos.git

源码编译
mvn -Prelease-nacos clean install -U -f pom.xml -Dmaven.test.skip=true

宿主机启动
/opt/Nacos/distribution/target/nacos/bin
sh startup.sh -m standalone

http://ip:8848/nacos/


3、Dockerfile
注意 : 在/opt/Nacos目录下创建 Dockerfile 和 docker-entrypoint.sh
cat > Dockerfile
FROM openjdk:8u265-jdk
ADD ./distribution/target/nacos-server-*.zip /nacos-server.zip 
ADD ./docker-entrypoint.sh /docker-entrypoint.sh
RUN unzip nacos-server.zip
ENTRYPOINT ["/docker-entrypoint.sh"]

注意 : 需要对 docker-entrypoint.sh 文件是可以执行文件,chmod +x docker-entrypoint.sh,否则报错

cat > docker-entrypoint.sh
#!/bin/sh
echo "Starting nacos"
cd /nacos/bin
./startup.sh -m standalone 
# 切记,这里是需要阻塞住,否则进程退出,容器退出
cd ../logs
tail -f start.out

构建镜像 : 
[root@node1 Nacos]#  docker build -t bjbfd/nacos:v1 .
[+] Building 21.5s (9/9) FINISHED
 => [internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [internal] load build definition from Dockerfile                                                                                                                                                   0.0s
 => => transferring dockerfile: 239B                                                                                                                                                                   0.0s
 => [internal] load metadata for docker.io/library/openjdk:8u265-jdk                                                                                                                                  15.1s
 => CACHED [1/4] FROM docker.io/library/openjdk:8u265-jdk@sha256:23b65e5e3d71b4be99dbae646114092b226ad1887b3fb436d57566c68ebe4d8c                                                                      0.0s
 => [internal] load build context                                                                                                                                                                      1.5s
 => => transferring context: 149.29MB                                                                                                                                                                  1.5s
 => [2/4] ADD ./distribution/target/nacos-server-*.zip /nacos-server.zip                                                                                                                               1.7s
 => [3/4] ADD ./docker-entrypoint.sh /docker-entrypoint.sh                                                                                                                                             0.0s
 => [4/4] RUN unzip nacos-server.zip                                                                                                                                                                   1.9s
 => exporting to image                                                                                                                                                                                 1.2s
 => => exporting layers                                                                                                                                                                                1.2s
 => => writing image sha256:b9f9c5065aff494ced9ec7e7bf71e38cb909b84dc4c52b953a75633928a00fee                                                                                                           0.0s
 => => naming to docker.io/bjbfd/nacos:v1
[root@node1 test8]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
bjbfd/nacos   v1        b9f9c5065aff   33 seconds ago   819MB
root@node1 Nacos]#  docker run -itd -p 8080:8848 bjbfd/nacos:v1
36d3907526cc52472b40fa37185176b9961ec4aa25cacf2dbf60d54cd9c0723a
[root@node1 Nacos]# docker ps -a
CONTAINER ID   IMAGE            COMMAND                   CREATED          STATUS          PORTS                                       NAMES
36d3907526cc   bjbfd/nacos:v1   "/docker-entrypoint.…"   23 seconds ago   Up 22 seconds   0.0.0.0:8080->8848/tcp, :::8080->8848/tcp   objective_mcclintock

访问 :
http://ip:8080/nacos/

4、docker compose
cat > docker-compose.yml
version: "3.9"
services: 
  nacos:
    build:
      context: .
      dockerfile: Dockerfile
    image: bjbfd/nacos:v1 
    container_name: nacos 
    ports:
      - "8080:8848"

[root@node1 Nacos]# docker compose up -d
[+] Running 1/1
 ! nacos Warning                                                                                                                                                                                      33.2s
[+] Building 15.3s (9/9) FINISHED
 => [nacos internal] load build definition from Dockerfile                                                                                                                                             0.0s
 => => transferring dockerfile: 239B                                                                                                                                                                   0.0s
 => [nacos internal] load .dockerignore                                                                                                                                                                0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [nacos internal] load metadata for docker.io/library/openjdk:8u265-jdk                                                                                                                            15.2s
 => [nacos 1/4] FROM docker.io/library/openjdk:8u265-jdk@sha256:23b65e5e3d71b4be99dbae646114092b226ad1887b3fb436d57566c68ebe4d8c                                                                       0.0s
 => [nacos internal] load build context                                                                                                                                                                0.1s
 => => transferring context: 298B                                                                                                                                                                      0.1s
 => CACHED [nacos 2/4] ADD ./distribution/target/nacos-server-*.zip /nacos-server.zip                                                                                                                  0.0s
 => CACHED [nacos 3/4] ADD ./docker-entrypoint.sh /docker-entrypoint.sh                                                                                                                                0.0s
 => CACHED [nacos 4/4] RUN unzip nacos-server.zip                                                                                                                                                      0.0s
 => [nacos] exporting to image                                                                                                                                                                         0.0s
 => => exporting layers                                                                                                                                                                                0.0s
 => => writing image sha256:7683dc756e46379b7214fa99d113cfd74836a9b65b23129213e7a0332713eb9f                                                                                                           0.0s
 => => naming to docker.io/bjbfd/nacos:v1                                                                                                                                                              0.0s
[+] Running 1/1
 ✔ Container nacos  Started
[root@node1 Nacos]# docker compose ps
NAME                IMAGE               COMMAND                  SERVICE             CREATED             STATUS              PORTS
nacos               bjbfd/nacos:v1      "/docker-entrypoint.…"   nacos               31 seconds ago      Up 30 seconds       0.0.0.0:8080->8848/tcp, :::8080->8848/tcp
[root@node1 Nacos]#

访问 :
http://ip:8080/nacos/

8、Docker Swarm

1、Docker Swarm是什么?

Docker Swarm是Docker提出的集群产品

  • Docker Swarm包含两方面: 一个企业级的Docker安全集群,以及一个微服务应用编排引擎
  • 集群方面: Swarm将一个或多个Docker节点组织起来,使得用户能够以集群方式管理它们
  • 编排方面: Swarm提供了一套丰富的API使得部署和管理复杂的微服务应用变得易如反掌
  • Docker Swarm是一个基于Docker引擎之上的独立产品
  • 关于应用编排: Swarm中的最小调度单元是服务。当容器被封装在一个服务中时,我们称之为一个任务或一个副本,服务中增加了诸如扩缩容、滚动升级以及简单回滚等特性

2、Docker Swarm 特点

  • 去中心化:Swarm角色分为Manager和Worker节点,Manager节点故障不影响应用使用
  • 弹性伸缩:对于服务声明任务数,群管理器自动调整任务状态
  • 动态调整:Work节点故障,服务动态调整
  • 服务发现:每个服务分配唯一的DNS名称,并平衡正在运行的容器
  • 负载均衡:针对流量可以节点调试分配,实现流量负载均衡
  • 滚动更新:服务升级您可以将服务更新逐步应用于节点
  • 声明式配置: 使用声明式方法定义应用程序中各种服务的所需状态
  • 多主机网络:初始化或更新应用程序时会自动IP地址分配给覆盖网络上的容器

3、Docker Swarm整体架构

image.png

4、Docker Swarm入门体验

1、准备三台机器
1台做manager节点,manager生产环境的数量建议是3或者5台,因为使用Raft算法选举leader,所以奇数是最好的
2台worker节点

2、manager初始化
[root@master ~]# docker swarm init
Swarm initialized: current node (izergwaf4hy0kztbw5p1e9jf3) is now a manager.

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

    docker swarm join --token SWMTKN-1-2afgwq0jgfjxendejq25mw1ri7obmm6i2lvm3bokaqw4aam6m6-783ihier1a2oluszql4asix3d 172.24.251.133:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
[root@master ~]# docker swarm init --help

Usage:  docker swarm init [OPTIONS]

Initialize a swarm

Options:
      --advertise-addr string                  Advertised address (format: "<ip|interface>[:port]")
      --autolock                               Enable manager autolocking (requiring an unlock key to start a stopped manager)
      --availability string                    Availability of the node ("active", "pause", "drain") (default "active")
      --cert-expiry duration                   Validity period for node certificates (ns|us|ms|s|m|h) (default 2160h0m0s)
      --data-path-addr string                  Address or interface to use for data path traffic (format: "<ip|interface>")
      --data-path-port uint32                  Port number to use for data path traffic (1024 - 49151). If no value is set or is set to 0, the default port (4789) is used.
      --default-addr-pool ipNetSlice           default address pool in CIDR format (default [])
      --default-addr-pool-mask-length uint32   default address pool subnet mask length (default 24)
      --dispatcher-heartbeat duration          Dispatcher heartbeat period (ns|us|ms|s|m|h) (default 5s)
      --external-ca external-ca                Specifications of one or more certificate signing endpoints
      --force-new-cluster                      Force create a new cluster from current state
      --listen-addr node-addr                  Listen address (format: "<ip|interface>[:port]") (default 0.0.0.0:2377)
      --max-snapshots uint                     Number of additional Raft snapshots to retain
      --snapshot-interval uint                 Number of log entries between Raft snapshots (default 10000)
      --task-history-limit int                 Task history retention limit (default 5)

swarm init命令支持的参数包括 :
--advertise-addr string : 指定服务监听的地址和端口
--autolock : 自定锁定管理服务的启停操作,对服务进行启动或停止都需要通过口令来解锁
--availability string : 节点的可用性,包括active、pause、drain三种,默认为active
--cert-expiry duration : 根证书的过期时长,默认为90天
--data-path-addr string : 指定数据流量使用的网络接口或地址
--dispatcher-heartbeat duration : 分配组件的心跳时长,默认为5秒
--external-ca external-ca : 指定使用外部的证书签名服务地址
--force-new-cluster : 强制创建新集群
--max-snapshots uint : Raft协议进行快照的间隔(单位为事务个数),默认为10000个事务
--task-history-limit int : 任务历史的保留个数,默认为5

2、加入node节点(node节点运行)
node1加入
[root@node1 ~]# docker swarm join --token SWMTKN-1-2afgwq0jgfjxendejq25mw1ri7obmm6i2lvm3bokaqw4aam6m6-783ihier1a2oluszql4asix3d 172.24.251.133:2377
This node joined a swarm as a worker.

node2加入
[root@node1 ~]# docker swarm join --token SWMTKN-1-2afgwq0jgfjxendejq25mw1ri7obmm6i2lvm3bokaqw4aam6m6-783ihier1a2oluszql4asix3d 172.24.251.133:2377
This node joined a swarm as a worker.

3、master上查看节点列表
[root@master ~]# docker node ls
ID                            HOSTNAME   STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
izergwaf4hy0kztbw5p1e9jf3 *   master     Ready     Active         Leader           24.0.2
jfkybv8cgg6owjrjbxg63zjxx     node1      Ready     Active                          24.0.2
jdf30le3osp9v7up2fyei3av8     node2      Ready     Active                          24.0.2

3、docker swarm面向的是service
[root@master ~]# docker service ls
ID        NAME      MODE      REPLICAS   IMAGE     PORTS

4、node2节点脱离manager
[root@node2 ~]# docker swarm leave
Node left the swarm
[root@master ~]# docker node ls
ID                            HOSTNAME   STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
izergwaf4hy0kztbw5p1e9jf3 *   master     Ready     Active         Leader           24.0.2
jfkybv8cgg6owjrjbxg63zjxx     node1      Ready     Active                          24.0.2
jdf30le3osp9v7up2fyei3av8     node2      Down      Active                          24.0.2

注意 : 看到 node2 节点的状态是Down

5、删除node2节点
[root@master ~]# docker node ls
ID                            HOSTNAME   STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
izergwaf4hy0kztbw5p1e9jf3 *   master     Ready     Active         Leader           24.0.2
jfkybv8cgg6owjrjbxg63zjxx     node1      Ready     Active                          24.0.2
jdf30le3osp9v7up2fyei3av8     node2      Down      Active                          24.0.2
[root@master ~]# docker node rm jdf30le3osp9v7up2fyei3av8
jdf30le3osp9v7up2fyei3av8
[root@master ~]# docker node ls
ID                            HOSTNAME   STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
izergwaf4hy0kztbw5p1e9jf3 *   master     Ready     Active         Leader           24.0.2
jfkybv8cgg6owjrjbxg63zjxx     node1      Ready     Active                          24.0.2

6、解散集群
[root@master ~]# docker swarm leave --force
Node left the swarm.
[root@master ~]# docker node ls
Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.

5、Docker Service

docker swarm其实面向的是service,不再是容器。因为要对service进行集群task的副本调度(其实就是容器)。所以在swarm中是面向service的

1、service创建

replicated 模式

[root@master ~]# docker service create -p 8080:80 --replicas 2 --name nginx_service_replicated nginx
j7wri91btcxq7mxce077fwsgz
overall progress: 2 out of 2 tasks
1/2: running   [==================================================>]
2/2: running   [==================================================>]
verify: Service converged

注意 : 如果不指定--mode,默认就是replicated模式,可以看到2个副本会调度到两个接地那上,master节点也是可以进行任务调度的

global 模式

[root@master ~]# docker service create -p 8081:80 --mode global --name nginx_service_global nginx
z500vlnkjzkm63vs4bqz08fqj
overall progress: 3 out of 3 tasks
lh93hprufwp4: running   [==================================================>]
urtqanp49o5s: running   [==================================================>]
vjvoar0e7za3: running   [==================================================>]
verify: Service converged

注意 : --mode global,可以看到副本会调度到所有的节点上。说白了,其实global就是replicated是所有节点的一种特殊情况

2、查看service列表
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
z500vlnkjzkm   nginx_service_global       global       3/3        nginx:latest   *:8081->80/tcp
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp

看到我们上面其实是创建了两个service,nginx_service_replicated有两个副本,nginx_service_global有三个副本

3、查看service的task调度所在的节点
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
z500vlnkjzkm   nginx_service_global       global       3/3        nginx:latest   *:8081->80/tcp
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp
[root@master ~]#
[root@master ~]#
[root@master ~]# docker service ps j7wri91btcxq
ID             NAME                         IMAGE          NODE      DESIRED STATE   CURRENT STATE           ERROR     PORTS
5twojcu6bbce   nginx_service_replicated.1   nginx:latest   master    Running         Running 9 minutes ago
jdbfcn175fo4   nginx_service_replicated.2   nginx:latest   node1     Running         Running 9 minutes ago

看到 nginx_service_replicated service的task会调度在master和node1两个节点上

4、删除service
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
z500vlnkjzkm   nginx_service_global       global       3/3        nginx:latest   *:8081->80/tcp
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp
[root@master ~]# docker service rm z500vlnkjzkm
z500vlnkjzkm
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp

5、跟新service
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp
[root@master ~]# docker service update j7wri91btcxq --workdir /root
j7wri91btcxq
overall progress: 2 out of 2 tasks
1/2: running   [==================================================>]
2/2: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp

6、service扩缩容
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   2/2        nginx:latest   *:8080->80/tcp
[root@master ~]# docker service scale j7wri91btcxq=3
j7wri91btcxq scaled to 3
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   3/3        nginx:latest   *:8080->80/tcp
[root@master ~]# docker service ps j7wri91btcxq
ID             NAME                             IMAGE          NODE      DESIRED STATE   CURRENT STATE                 ERROR     PORTS
tp2gdterympd   nginx_service_replicated.1       nginx:latest   master    Running         Running 2 minutes ago
5twojcu6bbce    \_ nginx_service_replicated.1   nginx:latest   master    Shutdown        Shutdown 2 minutes ago
6fxsg0esqzcg   nginx_service_replicated.2       nginx:latest   node1     Running         Running about a minute ago
jdbfcn175fo4    \_ nginx_service_replicated.2   nginx:latest   node1     Shutdown        Shutdown about a minute ago
tnzhzayhijni   nginx_service_replicated.3       nginx:latest   node2     Running         Running 22 seconds ago

7、回滚service
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   3/3        nginx:latest   *:8080->80/tcp
[root@master ~]# docker service update --image nginx:1.15.0 nginx_service_replicated

nginx_service_replicated
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
[root@master ~]#
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   3/3        nginx:1.15.0   *:8080->80/tcp
[root@master ~]# docker service rollback nginx_service_replicated
nginx_service_replicated
rollback: manually requested rollback
overall progress: rolling back update: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   3/3        nginx:latest   *:8080->80/tcp

8、查看service日志
[root@master ~]# docker service ls
ID             NAME                       MODE         REPLICAS   IMAGE          PORTS
j7wri91btcxq   nginx_service_replicated   replicated   3/3        nginx:latest   *:8080->80/tcp
[root@master ~]# docker service logs nginx_service_replicated

注意 : 会把所有的节点的日志聚合到一起收集过来进行显示

9、查看service元数据
[root@master ~]# docker service inspect nginx_service_replicated
[
    {
        "ID": "j7wri91btcxq7mxce077fwsgz",
        "Version": {
            "Index": 138
        },
        "CreatedAt": "2023-06-10T08:55:56.379928496Z",
        "UpdatedAt": "2023-06-10T09:15:27.312362399Z",
        "Spec": {
            "Name": "nginx_service_replicated",
            "Labels": {},
            "TaskTemplate": {
                "ContainerSpec": {
                    "Image": "nginx:latest@sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31",
                    "Dir": "/root",
                    "Init": false,
                    "StopGracePeriod": 10000000000,
                    "DNSConfig": {},
                    "Isolation": "default"
                },
                "Resources": {
                    "Limits": {},
                    "Reservations": {}
                },
                "RestartPolicy": {
                    "Condition": "any",
                    "Delay": 5000000000,
                    "MaxAttempts": 0
                },
                "Placement": {
                    "Platforms": [
                        {
                            "Architecture": "amd64",
                            "OS": "linux"
                        },
                        {
                            "OS": "linux"
                        },
                        {
                            "OS": "linux"
                        },
                        {
                            "Architecture": "arm64",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "386",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "mips64le",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "ppc64le",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "s390x",
                            "OS": "linux"
                        }
                    ]
                },
                "ForceUpdate": 0,
                "Runtime": "container"
            },
            "Mode": {
                "Replicated": {
                    "Replicas": 3
                }
            },
            "UpdateConfig": {
                "Parallelism": 1,
                "FailureAction": "pause",
                "Monitor": 5000000000,
                "MaxFailureRatio": 0,
                "Order": "stop-first"
            },
            "RollbackConfig": {
                "Parallelism": 1,
                "FailureAction": "pause",
                "Monitor": 5000000000,
                "MaxFailureRatio": 0,
                "Order": "stop-first"
            },
            "EndpointSpec": {
                "Mode": "vip",
                "Ports": [
                    {
                        "Protocol": "tcp",
                        "TargetPort": 80,
                        "PublishedPort": 8080,
                        "PublishMode": "ingress"
                    }
                ]
            }
        },
        "PreviousSpec": {
            "Name": "nginx_service_replicated",
            "Labels": {},
            "TaskTemplate": {
                "ContainerSpec": {
                    "Image": "nginx:1.15.0@sha256:62a095e5da5f977b9f830adaf64d604c614024bf239d21068e4ca826d0d629a4",
                    "Dir": "/root",
                    "Init": false,
                    "DNSConfig": {},
                    "Isolation": "default"
                },
                "Resources": {
                    "Limits": {},
                    "Reservations": {}
                },
                "Placement": {
                    "Platforms": [
                        {
                            "Architecture": "amd64",
                            "OS": "linux"
                        },
                        {
                            "OS": "linux"
                        },
                        {
                            "Architecture": "arm64",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "386",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "ppc64le",
                            "OS": "linux"
                        },
                        {
                            "Architecture": "s390x",
                            "OS": "linux"
                        }
                    ]
                },
                "ForceUpdate": 0,
                "Runtime": "container"
            },
            "Mode": {
                "Replicated": {
                    "Replicas": 3
                }
            },
            "EndpointSpec": {
                "Mode": "vip",
                "Ports": [
                    {
                        "Protocol": "tcp",
                        "TargetPort": 80,
                        "PublishedPort": 8080,
                        "PublishMode": "ingress"
                    }
                ]
            }
        },
        "Endpoint": {
            "Spec": {
                "Mode": "vip",
                "Ports": [
                    {
                        "Protocol": "tcp",
                        "TargetPort": 80,
                        "PublishedPort": 8080,
                        "PublishMode": "ingress"
                    }
                ]
            },
            "Ports": [
                {
                    "Protocol": "tcp",
                    "TargetPort": 80,
                    "PublishedPort": 8080,
                    "PublishMode": "ingress"
                }
            ],
            "VirtualIPs": [
                {
                    "NetworkID": "my7b7ij5exe7a2o7psm0mizp6",
                    "Addr": "10.0.0.8/24"
                }
            ]
        },
        "UpdateStatus": {
            "State": "rollback_completed",
            "StartedAt": "2023-06-10T09:15:11.115228912Z",
            "CompletedAt": "2023-06-10T09:15:27.312317145Z",
            "Message": "rollback completed"
        }
    }
]

10、service访问
[root@master ~]# curl 127.0.0.1:8080
node1
[root@master ~]# curl 127.0.0.1:8080
master
[root@master ~]# curl 127.0.0.1:8080
node2
[root@master ~]# curl 127.0.0.1:8080
node1

6、Docker Swarm架构

1、Service & Task

服务(services)和任务(task)

服务是要在管理节点或工作节点上执行的任务的定义。它是swarm系统的中心结构,也是用户与 swarm交互的主要根源

replicated services (克隆服务),群管理器根据您在所需状态中设置的规模在节点之间分配特定数量的副本任务
global services (全局服务),swarm 在集群中的每个可用节点上为服务运行一个任务

一个任务携带一个Docker容器和在容器内运行的命令。它是swarm的最小调度单元。Manager节点根据服务规模中设置的副本数将任务分配给工作节点。一旦任务被分配给一个节点,它就不能移动到另一个节点。它只能在分配的节点上运行或失败

2、Service & Task & Container 整体架构

image.png

Swarm集群中节点分为两种 :

  • 管理节点(manager node):负责响应外部对集群的操作请求,并维持集群中资源,分发任务给工作节点。同时,多个管理节点之间通过Raft协议构成共识。一般推荐每个集群设置3个或5个管理节点
  • 工作节点(worker node):负责执行管理节点安排的具体任务。默认情况下,管理节点自身也同时是工作节点。每个工作节点上运行代理(agent)来汇报任务完成情况

image.png

Docker Swarm管理机制 :
容器是一个孤立的进程。在群体模式模型中,每个任务仅调用一个容器。任务类似于调度程序在其中放置容器的“插槽”。一旦容器处于活动状态,调度程序就会识别出该任务处于运行状态。如果容器未通过运行状况检查或终止,则任务将终止
image.png

3、Docker Service 创建

image.png

4、Docker Swarm Task任务状态

image.png

9、Docker Swarm网络

image.png
overlay_test : overlay网络,实现容器间东西向流量的网络。容器主要是通vxlan隧道进行互联
docker_gwbridge : 容器收发南北向报文的网络

1、linux network namespace

创建两个网络命名空间test1和test2,并创建虚拟网卡(veth pair) veth-test1,veth-test2,把虚拟网卡加入test1,test2命名空间。让两个网卡可以网络互通
image.png

1、创建network namespace
[root@master ~]# ip netns add test1
[root@master ~]# ip netns add test2

2、查看network namespace列表
[root@master ~]# ip netns
test2
test1

3、查看network namespace的网络接口信息
[root@master ~]# ip netns exec test1 ip link
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
[root@master ~]# ip netns exec test2 ip link
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

主要 : test1、test2这两个命名空间的网络连接的本地回环接口lo的状态为DOWN

4、启动loopback接口
[root@master ~]# ip netns exec test1 ip link set dev lo up
[root@master ~]# ip netns exec test2 ip link set dev lo up
[root@master ~]# ip netns exec test1 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
[root@master ~]# ip netns exec test2 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

注意 : test1和test2的lo网络接口均为UNKNOWN状态,并不是UP状态,这是因为网络接口未被连接

5、创建虚拟网卡(veth pair)
什么是veth pair ?
veth pair 不是一个设备,而是一对设备,以连接两个虚拟以太端口。操作veth pair,需要跟namespace一起配合。两个namespace test1/test2中各有一个tap组成veth pair,两个tap上配置的ip进行互ping,数据会从一头进入另一头出去,所以类似于网线的作用

创建一对veth pair
[root@master ~]# ip link add veth-test1 type veth peer name veth-test2
[root@master ~]# ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 00:16:3e:1d:5f:31 brd ff:ff:ff:ff:ff:ff
3: docker_gwbridge: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
    link/ether 02:42:e7:6d:f9:6b brd ff:ff:ff:ff:ff:ff
4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default
    link/ether 02:42:2b:6c:f4:27 brd ff:ff:ff:ff:ff:ff
9: veth9c11cd0@if8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker_gwbridge state UP mode DEFAULT group default
    link/ether 1e:d8:ad:00:dc:ec brd ff:ff:ff:ff:ff:ff link-netnsid 1
13: veth0d00e61@if12: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker_gwbridge state UP mode DEFAULT group default
    link/ether 96:fb:29:38:bb:9e brd ff:ff:ff:ff:ff:ff link-netnsid 2
14: veth-test2@veth-test1: <BROADCAST,MULTICAST,M-DOWN> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether 96:a0:b9:f9:a1:08 brd ff:ff:ff:ff:ff:ff
15: veth-test1@veth-test2: <BROADCAST,MULTICAST,M-DOWN> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether fe:8a:1e:b9:13:a5 brd ff:ff:ff:ff:ff:ff

注意 : 可以看到多了2个设备veth-test2@veth-test1、veth-test1@veth-test2,正式刚才创建的一对veth,接着将对这一对veth分配给test1和test2

6、设置veth的network namespace
[root@master ~]#ip link set veth-test1 netns test1
[root@master ~]#ip link set veth-test2 netns test2
[root@master ~]# ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 00:16:3e:1d:5f:31 brd ff:ff:ff:ff:ff:ff
3: docker_gwbridge: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
    link/ether 02:42:e7:6d:f9:6b brd ff:ff:ff:ff:ff:ff
4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default
    link/ether 02:42:2b:6c:f4:27 brd ff:ff:ff:ff:ff:ff
9: veth9c11cd0@if8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker_gwbridge state UP mode DEFAULT group default
    link/ether 1e:d8:ad:00:dc:ec brd ff:ff:ff:ff:ff:ff link-netnsid 1
13: veth0d00e61@if12: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker_gwbridge state UP mode DEFAULT group default
    link/ether 96:fb:29:38:bb:9e brd ff:ff:ff:ff:ff:ff link-netnsid 2
注意 : 已经看不到刚才的veth-test2@veth-test1、veth-test1@veth-test2了,去到各自命名空间去了

7、查看netns的ip地址
[root@master ~]# ip netns exec test1 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
15: veth-test1@if14: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether fe:8a:1e:b9:13:a5 brd ff:ff:ff:ff:ff:ff link-netnsid 1
[root@master ~]#
[root@master ~]#
[root@master ~]# ip netns exec test2 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
14: veth-test2@if15: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 96:a0:b9:f9:a1:08 brd ff:ff:ff:ff:ff:ff link-netnsid 0

8、veth-test1设置ip
[root@master ~]# ip netns exec test1 ip addr add 192.168.1.1/24 dev veth-test1
[root@master ~]# ip netns exec test1 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
15: veth-test1@if14: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether fe:8a:1e:b9:13:a5 brd ff:ff:ff:ff:ff:ff link-netnsid 1
    inet 192.168.1.1/24 scope global veth-test1
       valid_lft forever preferred_lft forever

9、veth-test2设置ip
[root@master ~]# ip netns exec test2 ip addr add 192.168.1.2/24 dev veth-test2
[root@master ~]# ip netns exec test2 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
14: veth-test2@if15: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 96:a0:b9:f9:a1:08 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 192.168.1.2/24 scope global veth-test2
       valid_lft forever preferred_lft forever

10、veth-test1 & veth-test2启动
[root@master ~]# ip netns exec test1 ip link set dev lo up
[root@master ~]# ip netns exec test1 ip link set dev veth-test1 up

[root@master ~]# ip netns exec test2 ip link set dev lo up
[root@master ~]# ip netns exec test2 ip link set dev veth-test2 up

11、测试网络互通
[root@master ~]# ip netns exec test1 ping 192.168.1.2
PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.
64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.078 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.052 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.051 ms
64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.054 ms
64 bytes from 192.168.1.2: icmp_seq=5 ttl=64 time=0.053 ms
64 bytes from 192.168.1.2: icmp_seq=6 ttl=64 time=0.051 ms
64 bytes from 192.168.1.2: icmp_seq=7 ttl=64 time=0.053 ms
64 bytes from 192.168.1.2: icmp_seq=8 ttl=64 time=0.051 ms
64 bytes from 192.168.1.2: icmp_seq=9 ttl=64 time=0.051 ms
^C
--- 192.168.1.2 ping statistics ---
9 packets transmitted, 9 received, 0% packet loss, time 7999ms
rtt min/avg/max/mdev = 0.051/0.054/0.078/0.012 ms

2、Docker Swarm Networking

1、create overlay(master节点上执行)
docker network create -d overlay --attachable --subnet 10.200.0.0/16 overlay_test

2、node1
docker run -d --name busybox --net overlay_test busybox sleep 36000

3、node2
docker run -d --name busybox --net overlay_test busybox sleep 36000

4、ip addr
[root@node1 opt]# docker exec busybox ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue 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
17: eth0@if18: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1450 qdisc noqueue
    link/ether 02:42:0a:c8:00:02 brd ff:ff:ff:ff:ff:ff
    inet 10.200.0.2/16 brd 10.200.255.255 scope global eth0
       valid_lft forever preferred_lft forever
19: eth1@if20: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
    link/ether 02:42:ac:12:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.3/16 brd 172.18.255.255 scope global eth1
       valid_lft forever preferred_lft forever

5、ip addr
[root@node1 opt]# docker exec busybox traceroute www.baidu.com
traceroute to www.baidu.com (180.101.50.188), 30 hops max, 46 byte packets
 1  172.18.0.1 (172.18.0.1)  0.013 ms  0.011 ms  0.010 ms
 2  10.33.248.138 (10.33.248.138)  2.737 ms  2.952 ms  10.130.64.138 (10.130.64.138)  2.453 ms
 3  11.73.8.230 (11.73.8.230)  2.755 ms  11.73.1.177 (11.73.1.177)  2.729 ms  11.73.8.38 (11.73.8.38)  2.719 ms
 4  10.102.225.121 (10.102.225.121)  2.556 ms  11.94.148.61 (11.94.148.61)  2.517 ms  10.68.90.21 (10.68.90.21)  2.568 ms
 5  11.94.144.94 (11.94.144.94)  4.869 ms  11.94.136.82 (11.94.136.82)  4.062 ms  11.94.128.190 (11.94.128.190)  4.245 ms
 6  10.102.42.49 (10.102.42.49)  5.207 ms  10.102.41.201 (10.102.41.201)  5.158 ms  10.102.42.49 (10.102.42.49)  5.079 ms
 7  115.236.101.74 (115.236.101.74)  5.150 ms

所以 : eth1@if20是南北向流量

[root@node1 opt]# docker exec busybox traceroute 10.200.0.4
traceroute to 10.200.0.4 (10.200.0.4), 30 hops max, 46 byte packets
 1  busybox.overlay_test (10.200.0.4)  0.320 ms  0.146 ms  0.136 ms

所以 : eth0@if18是东西向流量

10、Docker Swarm Scheduler

1、节点设置label
[root@master ~]# docker node update --label-add role=prod master
master
[root@master ~]# docker node update --label-add role=dev node1
node1
[root@master ~]# docker node update --label-add role=prod node2
node2

注意 : 是需要在manager节点进行设置节点label的

2、service设置调度约束

发布dev应用
[root@master ~]# docker service create --name nginx_dev --replicas 2 -p 8081:80 --constraint 'node.labels.role==dev' nginx

[root@master ~]# docker service ls
ID             NAME        MODE         REPLICAS   IMAGE          PORTS
jbtv7kyzojxa   nginx_dev   replicated   2/2        nginx:latest   *:8081->80/tcp
[root@master ~]# docker service ps nginx_dev
ID             NAME          IMAGE          NODE      DESIRED STATE   CURRENT STATE                ERROR     PORTS
86blsqqqfhxn   nginx_dev.1   nginx:latest   node1     Running         Running about a minute ago
qtma07srl1dx   nginx_dev.2   nginx:latest   node1     Running         Running about a minute ago

注意 : 看到其实两个task都调度到节点1上了,因为根据label标签来说,只有node1节点满足需求

发布prod应用
[root@master ~]# docker service create --name nginx_prod --replicas 2 -p 8081:80 --constraint 'node.labels.role == prod' nginx
k7xyzx50oq7ow6p8c0gtp0stk
overall progress: 2 out of 2 tasks
1/2: running   [==================================================>]
2/2: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service ls
ID             NAME         MODE         REPLICAS   IMAGE          PORTS
k7xyzx50oq7o   nginx_prod   replicated   2/2        nginx:latest   *:8081->80/tcp
[root@master ~]# docker service ps k7xyzx50oq7o
ID             NAME           IMAGE          NODE      DESIRED STATE   CURRENT STATE            ERROR     PORTS
xqryguozvfi5   nginx_prod.1   nginx:latest   master    Running         Running 33 seconds ago
p4ebijy9e67o   nginx_prod.2   nginx:latest   node2     Running         Running 33 seconds ago

注意 : 看到task被调度到master和node2节点,因为这两个节点的标签都是prod

3、删除标签
[root@master ~]# docker node update --label-rm role master
master
[root@master ~]# docker node update --label-rm role node1
node1
[root@master ~]# docker node update --label-rm role node2
node2

注意 : 如果 docker node update --label-add type=prod master
删除的时候可以是 docker node update --label-rm type master

4、设置节点状态
[root@master ~]# docker node ls
ID                            HOSTNAME   STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
tz1kc6zanvts58vonta45dbdh *   master     Ready     Active         Leader           24.0.2
ei57tr92ckotjtvbzw6ktt3cd     node1      Ready     Active                          24.0.2
k890am9ybvx67tvv67fpp96qo     node2      Ready     Active                          24.0.2

看到节点AVAILABILITY都是Active,可用状态分为 : active(激活)、drain(清空)和down(关闭状态)

比如说不想master节点进行任务调度 :
[root@master ~]# docker node update --availability drain master
master
[root@master ~]# docker node update --availability drain master
master
[root@master ~]# docker service create --mode global nginx
qo020gcj06otobsdh20hbsyta
overall progress: 2 out of 2 tasks
k890am9ybvx6: running   [==================================================>]
ei57tr92ckot: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service ls
ID             NAME                MODE         REPLICAS   IMAGE          PORTS
fm3qr30py4xh   nginx_dev           replicated   0/2        nginx:latest   *:8081->80/tcp
qo020gcj06ot   pedantic_margulis   global       2/2        nginx:latest
[root@master ~]# docker service ps qo020gcj06ot
ID             NAME                                          IMAGE          NODE      DESIRED STATE   CURRENT STATE            ERROR     PORTS
tfjaqqb0dosa   pedantic_margulis.ei57tr92ckotjtvbzw6ktt3cd   nginx:latest   node1     Running         Running 24 seconds ago
xl9jrr4hle0v   pedantic_margulis.k890am9ybvx67tvv67fpp96qo   nginx:latest   node2     Running         Running 23 seconds ago

注意 : 可以看到,global是所有节点都有一个任务,但是现在看master是没有任务的

可以看到如果让master节点变为active状态,就可以自动进行一个任务调度到master节点上 :
[root@master ~]# docker node update --availability active master
master
[root@master ~]# docker service ls
ID             NAME                MODE         REPLICAS   IMAGE          PORTS
fm3qr30py4xh   nginx_dev           replicated   0/2        nginx:latest   *:8081->80/tcp
qo020gcj06ot   pedantic_margulis   global       3/3        nginx:latest

5、预留资源
[root@master ~]# docker service create --reserve-memory 16G nginx
omohihqnkdfh23ug8anrfs3tf
overall progress: 0 out of 1 tasks
1/1: no suitable node (insufficient resources on 3 nodes)

注意 : master、node1和node2三个节点都是2核4G,没有足够的16G内存,所以不能进行正常的任务调度(不满足条件)

6、节点限制
[root@master ~]# docker service create --replicas-max-per-node 1 --replicas 6 --name nginx_max nginx
fu7ixocvg1caa9wvlzz8eix5j
overall progress: 3 out of 6 tasks
1/6: no suitable node (max replicas per node limit exceed)
2/6: running   [==================================================>]
3/6: no suitable node (max replicas per node limit exceed)
4/6: running   [==================================================>]
5/6: no suitable node (max replicas per node limit exceed)
6/6: running   [==================================================>]

注意 : 限制每个节点只能运行1个task,需要6个task。而只有三个节点,不能完整正常调度

[root@master ~]# docker service ls
ID             NAME        MODE         REPLICAS               IMAGE          PORTS
fu7ixocvg1ca   nginx_max   replicated   3/6 (max 1 per node)   nginx:latest

11、Docker Swarm负载均衡

1、Docker网络

  • Snadbox
    一个Sandbox包含了一个容器网络栈的配置。其中包括了对容器的网卡,路由以及对DNS设置的管理。通常,一个Sandbox的实现可以是一个Linux Namespace,一个FreeBSD Jail或者其他类似的东西。一个Sandbox可以包含多个处于不同Network的Endpont

    "NetworkSettings": {
              "Bridge": "",
              "SandboxID": "8c9ad9625c3e0a9519fdd42d8af1f9808e365f0a76f127a0908d22c896dd56e9",
              "HairpinMode": false,
              "LinkLocalIPv6Address": "",
              "LinkLocalIPv6PrefixLen": 0,
              "Ports": {
                  "80/tcp": null
              },
              "SandboxKey": "/var/run/docker/netns/8c9ad9625c3e",
  • Endpoint
    Endpint将一个Sandbox加入一个Network。Endpoint的实现可以是一个veth对,一个Open vSwith interval port或者棋类类似的东西。一个Endpoint只能属于一个Network和一个Sandbox
  • ingress_sbox
    ingress_sbox是swarm为每个节点默认创建的network namespace,用于连接ingress overlay network

2、服务发现和负载均衡

  • DNS
    内置DSN服务器127.0.0.11,通过DSN实现负载均衡
  • iptables
    iptables是Linux内核中可用的包过滤技术,它可以用于根据数据包的内容进行分类、修改和转发策略
  • LVS/IPVS
    LVS/IPVS(IP Virtual Server,IP虚拟服务器)是基于Netfilter的,作为Linux内核的一部分实现传输层负载均衡的技术,通常称为第4层LAN交换

3、基于DSN的负载均衡

image.png
image.png

[root@master ~]# docker network create -d overlay --attachable --subnet 10.200.0.0/16 mynet
u3d3ktxlolbcmdf0bdnw4fsmx
[root@master ~]# docker service create --endpoint-mode dnsrr --replicas 3 --name ngnix_server_dns --network mynet nginx
jyhekqhym3584g124f6i302qn
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service create --endpoint-mode dnsrr --replicas 1 --name myclient --network mynet httpd
co5khetzbvsgjlumknawtrcaw
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged
[root@master ~]# docker service ls
ID             NAME               MODE         REPLICAS   IMAGE          PORTS
co5khetzbvsg   myclient           replicated   1/1        httpd:latest
jyhekqhym358   ngnix_server_dns   replicated   3/3        nginx:latest

查看DNS
apt-get install dnsutils
注意 : 使用加速器 cp /etc/apt/sources.list /etc/apt/sources.list.bak && sed -i "s@http://deb.debian.org@http://mirrors.aliyun.com@g" /etc/apt/sources.list && rm -rf /var/lib/apt/lists/* && apt-get update

root@c97eb7dbf928:/usr/local/apache2# dig ngnix_server_dns

; <<>> DiG 9.16.37-Debian <<>> ngnix_server_dns
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19297
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;ngnix_server_dns.        IN    A

;; ANSWER SECTION:
ngnix_server_dns.    600    IN    A    10.200.0.2
ngnix_server_dns.    600    IN    A    10.200.0.3
ngnix_server_dns.    600    IN    A    10.200.0.4

;; Query time: 0 msec
;; SERVER: 127.0.0.11#53(127.0.0.11)
;; WHEN: Mon Jun 12 14:49:51 UTC 2023
;; MSG SIZE  rcvd: 130

root@c97eb7dbf928:/usr/local/apache2#

注意 : 需要先安装apt-get install iputils-ping
root@c97eb7dbf928:/usr/local/apache2# ping -c 1 ngnix_server_dns
PING ngnix_server_dns (10.200.0.4) 56(84) bytes of data.
64 bytes from ngnix_server_dns.3.nyqbwye093m1s0su8diso5knd.mynet (10.200.0.4): icmp_seq=1 ttl=64 time=0.081 ms

--- ngnix_server_dns ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.081/0.081/0.081/0.000 ms
root@c97eb7dbf928:/usr/local/apache2# ping -c 1 ngnix_server_dns
PING ngnix_server_dns (10.200.0.3) 56(84) bytes of data.
64 bytes from ngnix_server_dns.2.tm5tgawg01ii5ewy2np4oc12t.mynet (10.200.0.3): icmp_seq=1 ttl=64 time=0.397 ms

--- ngnix_server_dns ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.397/0.397/0.397/0.000 ms
root@c97eb7dbf928:/usr/local/apache2# ping -c 1 ngnix_server_dns
PING ngnix_server_dns (10.200.0.3) 56(84) bytes of data.
64 bytes from ngnix_server_dns.2.tm5tgawg01ii5ewy2np4oc12t.mynet (10.200.0.3): icmp_seq=1 ttl=64 time=0.260 ms

--- ngnix_server_dns ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.260/0.260/0.260/0.000 ms
root@c97eb7dbf928:/usr/local/apache2# ping -c 1 ngnix_server_dns
PING ngnix_server_dns (10.200.0.3) 56(84) bytes of data.
64 bytes from ngnix_server_dns.2.tm5tgawg01ii5ewy2np4oc12t.mynet (10.200.0.3): icmp_seq=1 ttl=64 time=0.245 ms

--- ngnix_server_dns ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.245/0.245/0.245/0.000 ms
root@c97eb7dbf928:/usr/local/apache2# ping -c 1 ngnix_server_dns
PING ngnix_server_dns (10.200.0.2) 56(84) bytes of data.
64 bytes from ngnix_server_dns.1.aiooypn6xljywwr55u7o0f82f.mynet (10.200.0.2): icmp_seq=1 ttl=64 time=0.401 ms

--- ngnix_server_dns ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.401/0.401/0.401/0.000 ms
root@c97eb7dbf928:/usr/local/apache2#

注意 : 可以看到是几乎是轮询的打

DNS总结:

  • 优点 : Docker版本大于1.10即原生支持容器集群内部的DNS的服务发现
  • 缺点 : 由于DNS TTL生效时间的存在,解析的结果不能做到实时,即使TTL设置为0,某些引用或者方法库会缓存DNS解析的结果,导致解析到已经失效的地址上

4、基于VIP的负载均衡(Docker默认方式)

image.png

  • DNS Server会将服务名 "nignx_server_dns" 解析到VIP,使用iptables和ipvs,VIP实现了2个服务端"nginx_server_dns"容器的负载均衡
  • 基于VIP的负载克服了DSN负载均衡的一些问题。在这种方法中,每个服务都有一个IP地址,并且该IP地址映射到与该服务关联的多个容器的IP地址。在这种情况下,与服务关联的服务IP不会改变,即使与该服务关联的容器死亡重新启动

    [root@master ~]# docker service create --replicas 1 --name client_vip --network mynet httpd
    njatfiemscxmpg4z16fhw3bm5
    overall progress: 1 out of 1 tasks
    1/1: running   [==================================================>]
    verify: Service converged
    [root@master ~]# docker service create --replicas 3 --name nginx_server_vip --network mynet nginx
    juvb4gp4hiy7uir06q5chbkg1
    overall progress: 3 out of 3 tasks
    1/3: running   [==================================================>]
    2/3: running   [==================================================>]
    3/3: running   [==================================================>]
    verify: Service converged
    root@8ee05f9b0eab:/usr/local/apache2# dig nginx_server_vip
    
    ; <<>> DiG 9.16.37-Debian <<>> nginx_server_vip
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 20446
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
    
    ;; QUESTION SECTION:
    ;nginx_server_vip.        IN    A
    
    ;; ANSWER SECTION:
    nginx_server_vip.    600    IN    A    10.200.0.12
    
    ;; Query time: 0 msec
    ;; SERVER: 127.0.0.11#53(127.0.0.11)
    ;; WHEN: Mon Jun 12 15:03:50 UTC 2023
    ;; MSG SIZE  rcvd: 66

    Service Ip "10.200.0.12" 使用Linux内核的iptables和IPVS负载均衡到2个容器。iptables实现防火墙规则,IPVS实现负载均衡

总结 :

  • 优点 : IPVS的方法是在Docker 1.12版本中采用的方法,主要是做到了4层的负载均衡,请求的转发实现在内核中,不需要二次拷贝请求和响应的内容,不需要解析和处理7层的HTTP协议,效率更高
  • 缺点 : 缺少7层负载均衡的支持,一个服务的负载均衡会占用主机的一个端口,服务于服务之间暴露的端口如果相同会产生冲突

5、路由网格

[root@master ~]# docker service create --replicas 3 --name nginx_mesh -p 8080:80 nginx
tpq71zwicp4szrp9t2ncsorzh
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged

通过宿主机访问(前提是将每个容器中的/usr/share/nginx/html/index.html修改一下)
[root@master ~]# curl 172.24.251.133:8080
node1
[root@master ~]# curl 172.24.251.133:8080
master
[root@master ~]# curl 172.24.251.133:8080
node2
[root@master ~]# curl 172.24.251.133:8080
node1

注意 : 当你在任何节点上访问8080端口时,swarm集群的负载均衡会将你的请求路由到活跃的容器中

Ingress服务发现

image.png

12、Docker Stack

1、什么是服务编排

严格来说,编排是比调度更广泛的一个概念 : 编排包括了调度,同时也包含了其他内容。比如,容器的故障重启(可能是由于容器本身不健康,也可能是宿主机出现了故障)。而调度仅仅是指,决定哪个容器运行在哪个宿主机上的过程

2、docker stack是什么

  • Docker有个编排工具docker compose,可以将组成某个应用的多个docker容器编排在一起,同时管理。同样在swarm集群中,可以使用docker stack将一组关联的服务进行编排管理
  • Docker Stack也是一个yaml文件,和一份docker-compse.yml文件差不多,指令基本一致。但是与compose相比其不支持bulid、links和network_mode。Docker Stack有一个新的指令deploy

3、docker stack例子

[root@master stack]# cat docker-compose.yml
version: '3.1'
services:
  nginx:
    restart: always
    image: nginx
    ports:
      - 8066:80
    deploy:
      mode: replicated # stack启动时,指定模式
      replicas: 2 # stack启动时,指定启动多少节点
[root@master stack]# ls
docker-compose.yml
[root@master stack]# docker stack deploy -c docker-compose.yml nginx
Ignoring unsupported options: restart

Creating network nginx_default
Creating service nginx_nginx
[root@master stack]# docker service ls
ID             NAME          MODE         REPLICAS   IMAGE          PORTS
5ayjdee75fir   nginx_nginx   replicated   2/2        nginx:latest   *:8066->80/tcp
[root@master stack]# docker service ps 5ayjdee75fir
ID             NAME            IMAGE          NODE      DESIRED STATE   CURRENT STATE            ERROR     PORTS
k1bbpa5v8a1l   nginx_nginx.1   nginx:latest   node1     Running         Running 26 seconds ago
asr7349lfioa   nginx_nginx.2   nginx:latest   master    Running         Running 26 seconds ago

4、docker stack命令

[root@master stack]# docker stack ls
NAME      SERVICES
nginx     1

注意 : 只要通过 docker stack deploy -c docker-compose.yml nginx 创建出来的,才能docker stack ls有stack

[root@master stack]# docker stack ps nginx
ID             NAME            IMAGE          NODE      DESIRED STATE   CURRENT STATE                ERROR     PORTS
k1bbpa5v8a1l   nginx_nginx.1   nginx:latest   node1     Running         Running about a minute ago
asr7349lfioa   nginx_nginx.2   nginx:latest   master    Running         Running about a minute ago
[root@master stack]# docker stack rm nginx
Removing service nginx_nginx
Removing network nginx_default

journey
32 声望23 粉丝

« 上一篇
Docker基础
下一篇 »
k8s