一、概述

在以前的博客分享和上一次的前后端开发中,我们已经初步安装和使用了docker,本次博客还是按照课件,来简单演示Docker的安装与应用。

Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中,然后发布到任何流行的 Linux或Windows 机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口。

在这里插入图片描述
观察Docker图标,其实很形象的解释了什么是Docker。在没有使用集装箱的情况下,我们需要考虑不同形状、尺寸的货物怎么安放,货物与货物之间是否能堆叠,这无疑是很繁琐的事情。现在有了集装箱(容器),我们就能将不同的货物放入集装箱之内这样就能以同样的方式来存放货物,实现了标准化。

Docker采用了集装箱原理,我们将程序放入到容器中,实现“一次封装,到处运行”,只要开发环境能跑,在其他任何流行的机器上都能运行。并且将程序丢入到容器中,很好的实现了程序与程序之间的隔离,避免了类似Java开发的程序和.net开发的程序安装在一个服务器上需要很多调试,有时还会产生冲突的情况。

Docker的应用场景:

Web 应用的自动化打包和发布。
自动化测试和持续集成、发布。
在服务型环境中部署和调整数据库或其他的后台应用。
从头编译或者扩展现有的 OpenShift 或 Cloud Foundry 平台来搭建自己的 PaaS 环境。



二、系统环境&项目介绍

1.系统环境

  1. 操作系统:CentOS7
  2. 硬件信息:使用virtual box配置虚拟机(内存3G、磁盘30G)
  3. 编程语言:GO 1.15.2

2.项目的任务要求

  1. Docker的安装
  2. Docker的安装与简单应用简单应用



三、Docker的安装

在之前的博客(本人关于Docker的分享文章)中,我使用的是yum直接安装,但这导致了Docker版本的老旧,从而导致了编译运行速度极慢。

因此,我更加推荐使用清华源来高效配置Docker环境:

如果你之前安装过 docker,请先删掉

sudo yum remove docker docker-common docker-selinux docker-engine

安装一些依赖

sudo yum install -y yum-utils device-mapper-persistent-data lvm2

根据你的发行版下载repo文件:

wget -O /etc/yum.repos.d/docker-ce.repo https://download.docker.com/linux/centos/docker-ce.repo

把软件仓库地址替换为 TUNA:

sudo sed -i 's+download.docker.com+mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo

最后安装:

sudo yum makecache fast
sudo yum install docker-ce

若输出Docker版本号出错如下:
在这里插入图片描述

可以重新启动并输出Docker的状态和版本号:

[root@localhost henryhzy]# systemctl daemon-reload
[root@localhost henryhzy]# sudo service docker restart
Redirecting to /bin/systemctl restart docker.service
[root@localhost henryhzy]# sudo service docker status
Redirecting to /bin/systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since 一 2020-12-21 22:50:34 CST; 7s ago
     Docs: https://docs.docker.com
 Main PID: 3648 (dockerd)
    Tasks: 8
   Memory: 157.5M
   CGroup: /system.slice/docker.service
           └─3648 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/cont...

12月 21 22:50:32 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:32 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:32 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:33 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:33 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:33 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:33 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:33 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
12月 21 22:50:34 localhost.localdomain systemd[1]: Started Docker Applicatio...
12月 21 22:50:34 localhost.localdomain dockerd[3648]: time="2020-12-21T22:50...
Hint: Some lines were ellipsized, use -l to show in full.
[root@localhost henryhzy]# docker version
Client: Docker Engine - Community
 Version:           20.10.1
 API version:       1.41
 Go version:        go1.13.15
 Git commit:        831ebea
 Built:             Tue Dec 15 04:37:17 2020
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.1
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       f001486
  Built:            Tue Dec 15 04:35:42 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.3
  GitCommit:        269548fa27e0089a8b8278fc4fc781d7f65a939b
 runc:
  Version:          1.0.0-rc92
  GitCommit:        ff819c7e9184c13b7c2607fe6c30ae19403a7aff
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0



四、Docker的简单应用

1. 运行第一个容器

运行镜像hello-world

[root@localhost henryhzy]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
Digest: sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

运行镜像ubuntu bash

要点:-it 参数,通过终端与进程(容器)交互,stdin,stdout,stderr定向到 TTY

docker run -it ubuntu bash

我在运行该指令时出现timeout error,因此自然而然地要更换Docker的国内镜像源,而Docker的国内镜像源的资源站比较丰富:
Docker中国区官方镜像:
https://registry.docker-cn.com
网易:
http://hub-mirror.c.163.com
ustc:
https://docker.mirrors.ustc.edu.cn
中国科技大学:
https://docker.mirrors.ustc.edu.cn
阿里云:
https://cr.console.aliyun.com/

[root@localhost henryhzy]# vim /etc/docker/daemon.json  # 创建或修改 /etc/docker/daemon.json 文件,修改为如下形式
{
    "registry-mirrors" : [
    "https://registry.docker-cn.com",
    "https://docker.mirrors.ustc.edu.cn",
    "http://hub-mirror.c.163.com",
    "https://cr.console.aliyun.com/"
  ]
}

[root@localhost henryhzy]# systemctl daemon-reload
[root@localhost henryhzy]# systemctl restart docker

然后安装Docker Ubuntu镜像:
在这里插入图片描述
此时再次运行Docker Ubuntu镜像即可:
在这里插入图片描述



2. Docker基本操作

  • 显示本地镜像库内容

    [root@localhost henryhzy]# docker images
    REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
    mysql         5.7       697daaecf703   10 days ago     448MB
    ubuntu        latest    f643c72bc252   3 weeks ago     72.9MB
    hello-world   latest    bf756fb1ae65   11 months ago   13.3kB
    hello-world   latest    bf756fb1ae65   11 months ago   13.3kB
    
  • 获得帮助

    [root@localhost henryhzy]# docker --help
    
    Usage:  docker [OPTIONS] COMMAND
    
    A self-sufficient runtime for containers
    
    Options:
          --config string      Location of client config files (default
                               "/root/.docker")
      -c, --context string     Name of the context to use to connect to the
                               daemon (overrides DOCKER_HOST env var and
                               default context set with "docker context use")
      -D, --debug              Enable debug mode
      -H, --host list          Daemon socket(s) to connect to
      -l, --log-level string   Set the logging level
                               ("debug"|"info"|"warn"|"error"|"fatal")
                               (default "info")
          --tls                Use TLS; implied by --tlsverify
          --tlscacert string   Trust certs signed only by this CA (default
                               "/root/.docker/ca.pem")
          --tlscert string     Path to TLS certificate file (default
                               "/root/.docker/cert.pem")
          --tlskey string      Path to TLS key file (default
                               "/root/.docker/key.pem")
          --tlsverify          Use TLS and verify the remote
      -v, --version            Print version information and quit
    
    Management Commands:
      app*        Docker App (Docker Inc., v0.9.1-beta3)
      builder     Manage builds
      buildx*     Build with BuildKit (Docker Inc., v0.5.0-docker)
      config      Manage Docker configs
      container   Manage containers
      context     Manage contexts
      image       Manage images
      manifest    Manage Docker image manifests and manifest lists
      network     Manage networks
      node        Manage Swarm nodes
      plugin      Manage plugins
      secret      Manage Docker secrets
      service     Manage services
      stack       Manage Docker stacks
      swarm       Manage Swarm
      system      Manage Docker
      trust       Manage trust on Docker images
      volume      Manage volumes
    
    Commands:
      attach      Attach local standard input, output, and error streams to a running container
      build       Build an image from a Dockerfile
      commit      Create a new image from a container's changes
      cp          Copy files/folders between a container and the local filesystem
      create      Create a new container
      diff        Inspect changes to files or directories on a container's filesystem
      events      Get real time events from the server
      exec        Run a command in a running container
      export      Export a container's filesystem as a tar archive
      history     Show the history of an image
      images      List images
      import      Import the contents from a tarball to create a filesystem image
      info        Display system-wide information
      inspect     Return low-level information on Docker objects
      kill        Kill one or more running containers
      load        Load an image from a tar archive or STDIN
      login       Log in to a Docker registry
      logout      Log out from a Docker registry
      logs        Fetch the logs of a container
      pause       Pause all processes within one or more containers
      port        List port mappings or a specific mapping for the container
      ps          List containers
      pull        Pull an image or a repository from a registry
      push        Push an image or a repository to a registry
      rename      Rename a container
      restart     Restart one or more containers
      rm          Remove one or more containers
      rmi         Remove one or more images
      run         Run a command in a new container
      save        Save one or more images to a tar archive (streamed to STDOUT by default)
      search      Search the Docker Hub for images
      start       Start one or more stopped containers
      stats       Display a live stream of container(s) resource usage statistics
      stop        Stop one or more running containers
      tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
      top         Display the running processes of a container
      unpause     Unpause all processes within one or more containers
      update      Update configuration of one or more containers
      version     Show the Docker version information
      wait        Block until one or more containers stop, then print their exit codes
    
    Run 'docker COMMAND --help' for more information on a command.
    
    To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
    
  • 显示运行中容器

    [root@localhost henryhzy]# docker ps
    CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
    
  • 显示所有容器(包含已中止)

      [root@localhost henryhzy]# docker ps -a
      CONTAINER ID   IMAGE         COMMAND    CREATED         STATUS                     PORTS     NAMES
      b6812c2d3cee   ubuntu        "bash"     4 minutes ago   Exited (0) 3 minutes ago             youthful_faraday
      99f729ea477b   hello-world   "/hello"   2 hours ago     Exited (0) 2 hours ago               xenodochial_noether
      2a1a3ae27a97   hello-world   "/hello"   4 days ago      Exited (0) 4 days ago                eager_lalande
    
  • 继续运行原容器并进入
    注意此处的NAMES要看情况而定,并且要重新运行Ubuntu bash时应当使用docker attach而非docker restart

    [root@localhost henryhzy]# docker restart exciting_wiles
    Error response from daemon: No such container: exciting_wiles
    [root@localhost henryhzy]# docker restart youthful_faraday
    youthful_faraday
    [root@localhost henryhzy]# docker attach youthful_faraday
    root@b6812c2d3cee:/# ls
    bin   dev  home  lib32  libx32  mnt  proc  run   srv  tmp  var
    boot  etc  lib   lib64  media   opt  root  sbin  sys  usr
    root@b6812c2d3cee:/# exit
    exit
    

3. MySQL与容器化

3.1 拉取MySQL镜像

  • 拉取MySQL镜像

    [root@localhost henryhzy]# docker pull mysql:5.7
    5.7: Pulling from library/mysql
    6ec7b7d162b2: Pulling fs layer 
    fedd960d3481: Pulling fs layer 
    7ab947313861: Pulling fs layer 
    64f92f19e638: Waiting 
    3e80b17bff96: Waiting 
    014e976799f9: Waiting 
    59ae84fee1b3: Waiting 
    7d1da2a18e2e: Waiting 
    301a28b700b9: Waiting 
    979b389fc71f: Waiting 
    403f729b1bad: Waiting 
    5.7: Pulling from library/mysql
    6ec7b7d162b2: Pull complete 
    fedd960d3481: Pull complete 
    7ab947313861: Pull complete 
    64f92f19e638: Pull complete 
    3e80b17bff96: Pull complete 
    014e976799f9: Pull complete 
    59ae84fee1b3: Pull complete 
    7d1da2a18e2e: Pull complete 
    301a28b700b9: Pull complete 
    979b389fc71f: Pull complete 
    403f729b1bad: Pull complete 
    Digest: sha256:d4ca82cee68dce98aa72a1c48b5ef5ce9f1538265831132187871b78e768aed1
    Status: Downloaded newer image for mysql:5.7
    docker.io/library/mysql:5.7
    

3.2 构建docker镜像

  • 编辑dockerfile

    mkdir mydock && cd mydock
    vim dockerfile
    #在文件中输入以下内容
    FROM ubuntu
    ENTRYPOINT ["top", "-b"]
    CMD ["-c"]
    
  • 构建镜像

    [root@localhost mydock]# docker build . -t hello
    Sending build context to Docker daemon  2.048kB
    Step 1/3 : FROM ubuntu
     ---> f643c72bc252
    Step 2/3 : ENTRYPOINT ["top", "-b"]
     ---> Running in 63397948b616
    Removing intermediate container 63397948b616
     ---> 27c96fbe2e5e
    Step 3/3 : CMD ["-c"]
     ---> Running in 56d1c9c8c7ff
    Removing intermediate container 56d1c9c8c7ff
     ---> 22faa7e802b9
    Successfully built 22faa7e802b9
    Successfully tagged hello:latest
    
  • 运行镜像

    [root@localhost mydock]# docker run -it --rm hello -H
    top - 17:07:13 up  2:46,  0 users,  load average: 0.27, 0.28, 0.16
    Threads:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
    %Cpu(s): 50.0 us, 50.0 sy,  0.0 ni,  0.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
    MiB Mem :   2846.0 total,    157.5 free,   1062.3 used,   1626.2 buff/cache
    MiB Swap:   3072.0 total,   3070.7 free,      1.3 used.   1563.3 avail Mem 
    
      PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
        1 root      20   0    5960   1704   1276 R   0.0   0.1   0:00.05 top
    
    top - 17:07:16 up  2:46,  0 users,  load average: 0.27, 0.28, 0.16
    Threads:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
    %Cpu(s): 18.3 us,  8.2 sy,  0.0 ni, 71.6 id,  1.2 wa,  0.0 hi,  0.8 si,  0.0 st
    MiB Mem :   2846.0 total,    158.4 free,   1061.3 used,   1626.2 buff/cache
    MiB Swap:   3072.0 total,   3070.7 free,      1.3 used.   1564.2 avail Mem 
    
      PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
        1 root      20   0    5960   1704   1276 R   0.0   0.1   0:00.05 top
    
    top - 17:07:19 up  2:46,  0 users,  load average: 0.25, 0.27, 0.16
    Threads:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
    %Cpu(s): 14.5 us,  5.9 sy,  0.0 ni, 79.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
    MiB Mem :   2846.0 total,    158.4 free,   1061.3 used,   1626.2 buff/cache
    MiB Swap:   3072.0 total,   3070.7 free,      1.3 used.   1564.2 avail Mem 
    
      PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
        1 root      20   0    5960   1704   1276 R   0.3   0.1   0:00.06 top
    ...
    ...
    【持续输出】
    

3.3 MySQL容器使用

  • 启动服务器

    [root@localhost mydock]# docker run -p 3306:3306 --name mysql2 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7
    927714891d7cea9370930a8dd7e7fdfdaf97838063078e45c8aae4ab8e76069d
    
    [root@localhost mydock]# docker ps
    CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                               NAMES
    927714891d7c   mysql:5.7   "docker-entrypoint.s…"   48 seconds ago   Up 46 seconds   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql2
    
    
  • 启动MySQL客户端并退出

    [root@localhost mydock]# docker run -it --net host mysql:5.7 "sh"
    # mysql -h127.0.0.1 -P3306 -uroot -proot
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 2
    Server version: 5.7.32 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql> exit
    Bye
    # exit
    [root@localhost mydock]# 
    
    
  • 数据库文件位置:

    [root@localhost mydock]# docker exec -it mysql2 bash
    root@927714891d7c:/# ls /var/lib/mysql
    auto.cnf    client-cert.pem  ib_logfile0  ibtmp1	      private_key.pem  server-key.pem
    ca-key.pem  client-key.pem   ib_logfile1  mysql		      public_key.pem   sys
    ca.pem	    ib_buffer_pool   ibdata1	  performance_schema  server-cert.pem
    root@927714891d7c:/# exit
    exit
    
    [root@localhost mydock]# docker container prune -f
    Deleted Containers:
    d8ee403b5c90c3900a1a6be55cfe87f7cd3318028ba5cc0a87888649f2ad4524
    b6812c2d3cee25993252274c71ec2c0a38cf8b735ffff4de2f38670159d93050
    99f729ea477bdee1babf99afbd811d23bec0337db8874f963270ab38b17a8286
    2a1a3ae27a97e03fc773ef2c01d34a697d607c0b2639581cd7ae0546315d0f07
    
    Total reclaimed space: 34B
    
    [root@localhost mydock]# docker volume prune -f
    Deleted Volumes:
    5274edde97e9c2df7a46b7889626a3687d992eec31624b4b309d9b788400ba36
    
    Total reclaimed space: 0B
    
    [root@localhost mydock]# sudo docker volume ls
    DRIVER    VOLUME NAME
    local     daa3ec7dfd2e58d6dac5cf62ea5ef64183806a6cb386f6ff604310e4cd51c16c
    
    [root@localhost mydock]# 
    
  • 创建卷并挂载(挂载到/var/lib/mysql)

    [root@localhost mydock]# docker rm $(sudo docker ps -a -q) -f -v
    927714891d7c
    [root@localhost mydock]# docker volume create mydb
    mydb
    [root@localhost mydock]# docker run --name mysql2 -e MYSQL_ROOT_PASSWORD=root -v mydb:/var/lib/mysql -d mysql:5.7
    3eaa6e51b7fcdefdeba9e609c80d0af2d44271a47dfcf3a02affc8bf623a5257
    [root@localhost mydock]# 
    
  • 启动客户端连接服务器,并退出

    [root@localhost mydock]# docker run --name myclient --link mysql2:mysql -it mysql:5.7 bash
    root@56a4e5c99806:/# env
    MYSQL_PORT_33060_TCP_ADDR=172.17.0.2
    MYSQL_PORT=tcp://172.17.0.2:3306
    MYSQL_PORT_3306_TCP_ADDR=172.17.0.2
    MYSQL_NAME=/myclient/mysql
    MYSQL_ENV_MYSQL_ROOT_PASSWORD=root
    MYSQL_MAJOR=5.7
    MYSQL_PORT_3306_TCP_PORT=3306
    HOSTNAME=56a4e5c99806
    MYSQL_ENV_MYSQL_MAJOR=5.7
    MYSQL_PORT_3306_TCP=tcp://172.17.0.2:3306
    PWD=/
    HOME=/root
    MYSQL_ENV_GOSU_VERSION=1.12
    MYSQL_PORT_33060_TCP_PROTO=tcp
    MYSQL_VERSION=5.7.32-1debian10
    GOSU_VERSION=1.12
    TERM=xterm
    MYSQL_PORT_33060_TCP_PORT=33060
    MYSQL_PORT_3306_TCP_PROTO=tcp
    SHLVL=1
    MYSQL_PORT_33060_TCP=tcp://172.17.0.2:33060
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    MYSQL_ENV_MYSQL_VERSION=5.7.32-1debian10
    _=/usr/bin/env
    root@56a4e5c99806:/# mysql -hmysql -P3306 -uroot -proot
    mysql: [Warning] Using a password on the command line interface can be insecure.
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 2
    Server version: 5.7.32 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql> 
    mysql> exit
    Bye
    root@56a4e5c99806:/# exit
    exit
    
    [root@localhost mydock]# 
    

    说明:这里使用了--link连接两个容器;客户端容器内可以使用mysql这个别名访问

  • 挂载现有数据库

    • 官网案例:
    docker run -v "$PWD/data":/var/lib/mysql --user 1000:1000 --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 
    
  • 修改容器配置

    • 官网案例
    docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag
    

3.4 Docker compose与多容器应用自动化部署

  • 下载docker-compose(容器编排的原型):

    yum install docker-compose
    
  • 编写stack.yml如下:

    version: '3.1'
    services:
     db:
      image: mysql:5.7
      command: --default-authentication-plugin=mysql_native_password
      restart: always
      environment:
       MYSQL_ROOT_PASSWORD: 19970805
     adminer:
      image: adminer
      restart: always
      ports:
       - 8080:8080
    
  • 启动服务

    docker-compose -f stack.yml up -d
    

4 docker网络

  • 管理容器网络

    [root@localhost henryhzy]# docker network ls
    NETWORK ID     NAME      DRIVER    SCOPE
    3a01e95dea2f   bridge    bridge    local
    5fd9221111e1   host      host      local
    05cfa60a0d11   none      null      local
    
    
  • 自定义容器网络,备制支持ifconfigping命令的ubuntu容器

    [root@localhost henryhzy]# docker run --name unet -it --rm ubuntu bash
    
    root@0774b9ce2310:/# apt-get update
    Get:1 http://security.ubuntu.com/ubuntu focal-security InRelease [109 kB]
    Get:2 http://archive.ubuntu.com/ubuntu focal InRelease [265 kB]
    Get:3 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [495 kB]
    Get:4 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
    Get:5 http://security.ubuntu.com/ubuntu focal-security/restricted amd64 Packages [103 kB]
    Get:6 http://archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
    Get:7 http://security.ubuntu.com/ubuntu focal-security/universe amd64 Packages [645 kB]
    Get:8 http://archive.ubuntu.com/ubuntu focal/restricted amd64 Packages [33.4 kB]
    Get:9 http://archive.ubuntu.com/ubuntu focal/main amd64 Packages [1275 kB]
    Get:10 http://security.ubuntu.com/ubuntu focal-security/multiverse amd64 Packages [1167 B]
    Get:11 http://archive.ubuntu.com/ubuntu focal/multiverse amd64 Packages [177 kB]
    Get:12 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages [11.3 MB]
    Get:13 http://archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 Packages [30.4 kB]
    Get:14 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [136 kB]
    Get:15 http://archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [885 kB]
    Get:16 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [885 kB]
    Get:17 http://archive.ubuntu.com/ubuntu focal-backports/universe amd64 Packages [4250 B]
    Fetched 16.6 MB in 1min 29s (186 kB/s)                                         
    Reading package lists... Done
    
    root@0774b9ce2310:/# apt-get install net-tools
    Reading package lists... Done
    Building dependency tree       
    Reading state information... Done
    The following NEW packages will be installed:
      net-tools
    0 upgraded, 1 newly installed, 0 to remove and 2 not upgraded.
    Need to get 196 kB of archives.
    After this operation, 864 kB of additional disk space will be used.
    Get:1 http://archive.ubuntu.com/ubuntu focal/main amd64 net-tools amd64 1.60+git20180626.aebd88e-1ubuntu1 [196 kB]
    Fetched 196 kB in 1s (348 kB/s)
    debconf: delaying package configuration, since apt-utils is not installed
    Selecting previously unselected package net-tools.
    (Reading database ... 4121 files and directories currently installed.)
    Preparing to unpack .../net-tools_1.60+git20180626.aebd88e-1ubuntu1_amd64.deb ...
    Unpacking net-tools (1.60+git20180626.aebd88e-1ubuntu1) ...
    Setting up net-tools (1.60+git20180626.aebd88e-1ubuntu1) ...
    root@0774b9ce2310:/# apt-get install net-tools
    Reading package lists... Done
    Building dependency tree       
    Reading state information... Done
    net-tools is already the newest version (1.60+git20180626.aebd88e-1ubuntu1).
    0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
    root@0774b9ce2310:/# apt-get install iputils-ping -y
    Reading package lists... Done
    Building dependency tree       
    Reading state information... Done
    The following additional packages will be installed:
      libcap2 libcap2-bin libpam-cap
    The following NEW packages will be installed:
      iputils-ping libcap2 libcap2-bin libpam-cap
    0 upgraded, 4 newly installed, 0 to remove and 2 not upgraded.
    Need to get 90.5 kB of archives.
    After this operation, 333 kB of additional disk space will be used.
    Get:1 http://archive.ubuntu.com/ubuntu focal/main amd64 libcap2 amd64 1:2.32-1 [15.9 kB]
    Get:2 http://archive.ubuntu.com/ubuntu focal/main amd64 libcap2-bin amd64 1:2.32-1 [26.2 kB]
    Get:3 http://archive.ubuntu.com/ubuntu focal/main amd64 iputils-ping amd64 3:20190709-3 [40.1 kB]
    Get:4 http://archive.ubuntu.com/ubuntu focal/main amd64 libpam-cap amd64 1:2.32-1 [8352 B]
    Fetched 90.5 kB in 2s (51.6 kB/s)      
    debconf: delaying package configuration, since apt-utils is not installed
    Selecting previously unselected package libcap2:amd64.
    (Reading database ... 4170 files and directories currently installed.)
    Preparing to unpack .../libcap2_1%3a2.32-1_amd64.deb ...
    Unpacking libcap2:amd64 (1:2.32-1) ...
    Selecting previously unselected package libcap2-bin.
    Preparing to unpack .../libcap2-bin_1%3a2.32-1_amd64.deb ...
    Unpacking libcap2-bin (1:2.32-1) ...
    Selecting previously unselected package iputils-ping.
    Preparing to unpack .../iputils-ping_3%3a20190709-3_amd64.deb ...
    Unpacking iputils-ping (3:20190709-3) ...
    Selecting previously unselected package libpam-cap:amd64.
    Preparing to unpack .../libpam-cap_1%3a2.32-1_amd64.deb ...
    Unpacking libpam-cap:amd64 (1:2.32-1) ...
    Setting up libcap2:amd64 (1:2.32-1) ...
    Setting up libcap2-bin (1:2.32-1) ...
    Setting up libpam-cap:amd64 (1:2.32-1) ...
    debconf: unable to initialize frontend: Dialog
    debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76.)
    debconf: falling back to frontend: Readline
    debconf: unable to initialize frontend: Readline
    debconf: (Can't locate Term/ReadLine.pm in @INC (you may need to install the Term::ReadLine module) (@INC contains: /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.30.0 /usr/local/share/perl/5.30.0 /usr/lib/x86_64-linux-gnu/perl5/5.30 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.30 /usr/share/perl/5.30 /usr/local/lib/site_perl /usr/lib/x86_64-linux-gnu/perl-base) at /usr/share/perl5/Debconf/FrontEnd/Readline.pm line 7.)
    debconf: falling back to frontend: Teletype
    Setting up iputils-ping (3:20190709-3) ...
    Processing triggers for libc-bin (2.31-0ubuntu9.1) ...
    
    root@0774b9ce2310:/# ifconfig
    eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255
            ether 02:42:ac:11:00:03  txqueuelen 0  (Ethernet)
            RX packets 7235  bytes 17286356 (17.2 MB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 7206  bytes 395732 (395.7 KB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    
    lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
            inet 127.0.0.1  netmask 255.0.0.0
            loop  txqueuelen 1000  (Local Loopback)
            RX packets 0  bytes 0 (0.0 B)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 0  bytes 0 (0.0 B)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
            
    root@0774b9ce2310:/# ping <your host ip>  //可ping成功 隐藏ip信息
    

    打开另一个终端窗口,由容器制作镜像

    [root@localhost henryhzy]# docker commit unet ubuntu:net
    sha256:aa7870b2dcb8eee7357aac8533a3e7e78313358c0532ea5dea7cec4a2907ae1b
    
  • 创建自定义网络

    [root@localhost henryhzy]# docker network create mynet
    4a4fa10b06e69fd3bcf4e1b3d53206768ed57601721bb2b78eb84177ea67da8b
    
  • 在另外两个窗口分别创建u1,u2容器网络,并使用以下命令:

    docker run --name u1 -it -p 8080:80 --net mynet --rm ubuntu:net bash
    docker run --name u2 --net mynet -it --rm ubuntu:net bash
    

    在这里插入图片描述

    [root@localhost henryhzy]# docker inspect u1
    [
        {
            "Id": "3615ba75666b105ffb19bf3975587b6e46e5146186f6678de2db52a77ad9fadf",
            "Created": "2020-12-21T17:45:20.647669834Z",
            "Path": "bash",
            "Args": [],
            "State": {
                "Status": "running",
                "Running": true,
                "Paused": false,
                "Restarting": false,
                "OOMKilled": false,
                "Dead": false,
                "Pid": 10571,
                "ExitCode": 0,
                "Error": "",
                "StartedAt": "2020-12-21T17:45:22.69888905Z",
                "FinishedAt": "0001-01-01T00:00:00Z"
            },
            "Image": "sha256:aa7870b2dcb8eee7357aac8533a3e7e78313358c0532ea5dea7cec4a2907ae1b",
            "ResolvConfPath": "/var/lib/docker/containers/3615ba75666b105ffb19bf3975587b6e46e5146186f6678de2db52a77ad9fadf/resolv.conf",
            "HostnamePath": "/var/lib/docker/containers/3615ba75666b105ffb19bf3975587b6e46e5146186f6678de2db52a77ad9fadf/hostname",
            "HostsPath": "/var/lib/docker/containers/3615ba75666b105ffb19bf3975587b6e46e5146186f6678de2db52a77ad9fadf/hosts",
            "LogPath": "/var/lib/docker/containers/3615ba75666b105ffb19bf3975587b6e46e5146186f6678de2db52a77ad9fadf/3615ba75666b105ffb19bf3975587b6e46e5146186f6678de2db52a77ad9fadf-json.log",
            "Name": "/u1",
            "RestartCount": 0,
            "Driver": "overlay2",
            "Platform": "linux",
            "MountLabel": "",
            "ProcessLabel": "",
            "AppArmorProfile": "",
            "ExecIDs": null,
            "HostConfig": {
                "Binds": null,
                "ContainerIDFile": "",
                "LogConfig": {
                    "Type": "json-file",
                    "Config": {}
                },
                "NetworkMode": "mynet",
                "PortBindings": {
                    "80/tcp": [
                        {
                            "HostIp": "",
                            "HostPort": "8080"
                        }
                    ]
                },
                "RestartPolicy": {
                    "Name": "no",
                    "MaximumRetryCount": 0
                },
                "AutoRemove": true,
                "VolumeDriver": "",
                "VolumesFrom": null,
                "CapAdd": null,
                "CapDrop": null,
                "CgroupnsMode": "host",
                "Dns": [],
                "DnsOptions": [],
                "DnsSearch": [],
                "ExtraHosts": null,
                "GroupAdd": null,
                "IpcMode": "private",
                "Cgroup": "",
                "Links": null,
                "OomScoreAdj": 0,
                "PidMode": "",
                "Privileged": false,
                "PublishAllPorts": false,
                "ReadonlyRootfs": false,
                "SecurityOpt": null,
                "UTSMode": "",
                "UsernsMode": "",
                "ShmSize": 67108864,
                "Runtime": "runc",
                "ConsoleSize": [
                    0,
                    0
                ],
                "Isolation": "",
                "CpuShares": 0,
                "Memory": 0,
                "NanoCpus": 0,
                "CgroupParent": "",
                "BlkioWeight": 0,
                "BlkioWeightDevice": [],
                "BlkioDeviceReadBps": null,
                "BlkioDeviceWriteBps": null,
                "BlkioDeviceReadIOps": null,
                "BlkioDeviceWriteIOps": null,
                "CpuPeriod": 0,
                "CpuQuota": 0,
                "CpuRealtimePeriod": 0,
                "CpuRealtimeRuntime": 0,
                "CpusetCpus": "",
                "CpusetMems": "",
                "Devices": [],
                "DeviceCgroupRules": null,
                "DeviceRequests": null,
                "KernelMemory": 0,
                "KernelMemoryTCP": 0,
                "MemoryReservation": 0,
                "MemorySwap": 0,
                "MemorySwappiness": null,
                "OomKillDisable": false,
                "PidsLimit": null,
                "Ulimits": null,
                "CpuCount": 0,
                "CpuPercent": 0,
                "IOMaximumIOps": 0,
                "IOMaximumBandwidth": 0,
                "MaskedPaths": [
                    "/proc/asound",
                    "/proc/acpi",
                    "/proc/kcore",
                    "/proc/keys",
                    "/proc/latency_stats",
                    "/proc/timer_list",
                    "/proc/timer_stats",
                    "/proc/sched_debug",
                    "/proc/scsi",
                    "/sys/firmware"
                ],
                "ReadonlyPaths": [
                    "/proc/bus",
                    "/proc/fs",
                    "/proc/irq",
                    "/proc/sys",
                    "/proc/sysrq-trigger"
                ]
            },
            "GraphDriver": {
                "Data": {
                    "LowerDir": "/var/lib/docker/overlay2/a1a968eabfe8f593a62137c6b5abc4e772022c59006ba66f8f4a3a9fe697383f-init/diff:/var/lib/docker/overlay2/287cc08a344ff98b7a49739683bfdecee3f1f762f2ae57eb6ccb17bf6c7bee84/diff:/var/lib/docker/overlay2/d6be398a6c8c4c7a4c92e512744048789f990992ef6609dbe94306feb93ba6ad/diff:/var/lib/docker/overlay2/f866e66d90ab2c229a8af7960010e0530408422b5d7b65615acd5ba63da3baa2/diff:/var/lib/docker/overlay2/c1b551a6ca25d09a603c5a883e22e52ae31b33314afedae97a0b8079a02f9a2b/diff",
                    "MergedDir": "/var/lib/docker/overlay2/a1a968eabfe8f593a62137c6b5abc4e772022c59006ba66f8f4a3a9fe697383f/merged",
                    "UpperDir": "/var/lib/docker/overlay2/a1a968eabfe8f593a62137c6b5abc4e772022c59006ba66f8f4a3a9fe697383f/diff",
                    "WorkDir": "/var/lib/docker/overlay2/a1a968eabfe8f593a62137c6b5abc4e772022c59006ba66f8f4a3a9fe697383f/work"
                },
                "Name": "overlay2"
            },
            "Mounts": [],
            "Config": {
                "Hostname": "3615ba75666b",
                "Domainname": "",
                "User": "",
                "AttachStdin": true,
                "AttachStdout": true,
                "AttachStderr": true,
                "ExposedPorts": {
                    "80/tcp": {}
                },
                "Tty": true,
                "OpenStdin": true,
                "StdinOnce": true,
                "Env": [
                    "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
                ],
                "Cmd": [
                    "bash"
                ],
                "Image": "ubuntu:net",
                "Volumes": null,
                "WorkingDir": "",
                "Entrypoint": null,
                "OnBuild": null,
                "Labels": {}
            },
            "NetworkSettings": {
                "Bridge": "",
                "SandboxID": "109f19b7b72e8ea0e4f213da5b50bb12b565b89a73b3cfc227604d1e977f83a7",
                "HairpinMode": false,
                "LinkLocalIPv6Address": "",
                "LinkLocalIPv6PrefixLen": 0,
                "Ports": {
                    "80/tcp": [
                        {
                            "HostIp": "0.0.0.0",
                            "HostPort": "8080"
                        }
                    ]
                },
                "SandboxKey": "/var/run/docker/netns/109f19b7b72e",
                "SecondaryIPAddresses": null,
                "SecondaryIPv6Addresses": null,
                "EndpointID": "",
                "Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "IPAddress": "",
                "IPPrefixLen": 0,
                "IPv6Gateway": "",
                "MacAddress": "",
                "Networks": {
                    "mynet": {
                        "IPAMConfig": null,
                        "Links": null,
                        "Aliases": [
                            "3615ba75666b"
                        ],
                        "NetworkID": "4a4fa10b06e69fd3bcf4e1b3d53206768ed57601721bb2b78eb84177ea67da8b",
                        "EndpointID": "566e131813573a95ec5edc8905f80b61a1d3f4f1cde7a0e5030bcd37c0b377e2",
                        "Gateway": "172.18.0.1",
                        "IPAddress": "172.18.0.2",
                        "IPPrefixLen": 16,
                        "IPv6Gateway": "",
                        "GlobalIPv6Address": "",
                        "GlobalIPv6PrefixLen": 0,
                        "MacAddress": "02:42:ac:12:00:02",
                        "DriverOpts": null
                    }
                }
            }
        }
    ]
    [root@localhost henryhzy]# docker network connect bridge u1
    [root@localhost henryhzy]# docker network disconnect mynet u1
    

5. Docker仓库 (Registry)

以阿里云容器镜像服务的教程如下:

阿里云容器镜像服务(免费)实践

– 访问 https://cr.console.aliyun.com

– 用淘宝或注册一个账号

– 选择“容器镜像服务”

– 常用仓库操作:如上传 hello-world 镜像

• 登陆 docker login --username= registry.cn-shenzhen.aliyuncs.com 

• 标签 docker tag hello-world registry.cn-shenzhen.aliyuncs.com/pmlpml/repo:helloworld 

• 上传 docker push registry.cn-shenzhen.aliyuncs.com/pmlpml/repo:hello-world 

• 下载 docker push registry.cn-shenzhen.aliyuncs.com/pmlpml/repo:hello-world 

• 标签 docker tag registry.cn-shenzhen.aliyuncs.com/pmlpml/repo:hello-world helloworld 

• 删除 docker rmi registry.cn-shenzhen.aliyuncs.com/pmlpml/repo:hello-world 

• 运行 docker run --rm hello-world • 退出 docker logout registry.cn-shenzhen.aliyuncs.com 

• 检查docker的状态

~]# docker info … … 

~]# docker info --format {{.ServerVersion}} 

• 查看容器内进程

– Docker top 

– Docker stats 

• 容器详细信息

~]# docker inspect … … 

~]# docker inspect -f '{{.NetworkSettings.IPAddress}}' 084f46eddf33 172.17.0.2 

• 容器的日志

– 容器应用的 stdout 与 stderr 输出 

• 容器日志查看

 ~]# docker logs 084f46eddf33 

root@084f46eddf33:/# ll 

total 12 

drwxr-xr-x. 1 root root 43 Dec 13 13:46 ./ 

drwxr-xr-x. 1 root root 43 Dec 13 13:46 ../ 

-rwxr-xr-x. 1 root root 0 Dec 13 13:46 .dockerenv* 

drwxr-xr-x. 2 root root 4096 Dec 12 03:44 bin/ 

…

~]# docker logs --tail 2 084f46eddf33 

drwxr-xr-x. 10 root root 97 Dec 10 08:42 usr/ 

drwxr-xr-x. 11 root root 4096 Dec 10 08:42 var/ 

• 日志的重要性!
– 调试、分析



五、References

  1. 课件
  2. 本人关于Docker的分享文章
  3. 本人应用了Docker的前后端开发工程项目
  4. Docker清华源
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐