日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Docker的安装、镜像源更换与简单应用

發布時間:2023/11/28 生活经验 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Docker的安装、镜像源更换与简单应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Docker的安裝、鏡像源更換與簡單應用【閱讀時間:約20分鐘】

  • 一、概述
  • 二、系統環境&項目介紹
    • 1.系統環境
    • 2.項目的任務要求
  • 三、Docker的安裝
  • 四、Docker的簡單應用
    • 1. 運行第一個容器
    • 2. Docker基本操作
    • 3. MySQL與容器化
      • 3.1 拉取MySQL鏡像
      • 3.2 構建docker鏡像
      • 3.3 MySQL容器使用
      • 3.4 Docker compose與多容器應用自動化部署
    • 4 docker網絡
    • 5. Docker倉庫 (Registry)
  • 五、References



一、概述

在以前的博客分享和上一次的前后端開發中,我們已經初步安裝和使用了docker,本次博客還是按照課件,來簡單演示Docker的安裝與應用。

Docker 是一個開源的應用容器引擎,讓開發者可以打包他們的應用以及依賴包到一個可移植的鏡像中,然后發布到任何流行的 Linux或Windows 機器上,也可以實現虛擬化。容器是完全使用沙箱機制,相互之間不會有任何接口。


觀察Docker圖標,其實很形象的解釋了什么是Docker。在沒有使用集裝箱的情況下,我們需要考慮不同形狀、尺寸的貨物怎么安放,貨物與貨物之間是否能堆疊,這無疑是很繁瑣的事情?,F在有了集裝箱(容器),我們就能將不同的貨物放入集裝箱之內這樣就能以同樣的方式來存放貨物,實現了標準化。

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 EngineLoaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)Active: active (running) since 一 2020-12-21 22:50:34 CST; 7s agoDocs: https://docs.docker.comMain PID: 3648 (dockerd)Tasks: 8Memory: 157.5MCGroup: /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 - CommunityVersion:           20.10.1API version:       1.41Go version:        go1.13.15Git commit:        831ebeaBuilt:             Tue Dec 15 04:37:17 2020OS/Arch:           linux/amd64Context:           defaultExperimental:      trueServer: Docker Engine - CommunityEngine:Version:          20.10.1API version:      1.41 (minimum version 1.12)Go version:       go1.13.15Git commit:       f001486Built:            Tue Dec 15 04:35:42 2020OS/Arch:          linux/amd64Experimental:     falsecontainerd:Version:          1.4.3GitCommit:        269548fa27e0089a8b8278fc4fc781d7f65a939brunc:Version:          1.0.0-rc92GitCommit:        ff819c7e9184c13b7c2607fe6c30ae19403a7affdocker-init:Version:          0.19.0GitCommit:        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:latestHello 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 theexecutable that produces the output you are currently reading.4. The Docker daemon streamed that output to the Docker client, which sent itto your terminal.To try something more ambitious, you can run an Ubuntu container with:$ docker run -it ubuntu bashShare 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 --helpUsage:  docker [OPTIONS] COMMANDA self-sufficient runtime for containersOptions:--config string      Location of client config files (default"/root/.docker")-c, --context string     Name of the context to use to connect to thedaemon (overrides DOCKER_HOST env var anddefault 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 quitManagement Commands:app*        Docker App (Docker Inc., v0.9.1-beta3)builder     Manage buildsbuildx*     Build with BuildKit (Docker Inc., v0.5.0-docker)config      Manage Docker configscontainer   Manage containerscontext     Manage contextsimage       Manage imagesmanifest    Manage Docker image manifests and manifest listsnetwork     Manage networksnode        Manage Swarm nodesplugin      Manage pluginssecret      Manage Docker secretsservice     Manage servicesstack       Manage Docker stacksswarm       Manage Swarmsystem      Manage Dockertrust       Manage trust on Docker imagesvolume      Manage volumesCommands:attach      Attach local standard input, output, and error streams to a running containerbuild       Build an image from a Dockerfilecommit      Create a new image from a container's changescp          Copy files/folders between a container and the local filesystemcreate      Create a new containerdiff        Inspect changes to files or directories on a container's filesystemevents      Get real time events from the serverexec        Run a command in a running containerexport      Export a container's filesystem as a tar archivehistory     Show the history of an imageimages      List imagesimport      Import the contents from a tarball to create a filesystem imageinfo        Display system-wide informationinspect     Return low-level information on Docker objectskill        Kill one or more running containersload        Load an image from a tar archive or STDINlogin       Log in to a Docker registrylogout      Log out from a Docker registrylogs        Fetch the logs of a containerpause       Pause all processes within one or more containersport        List port mappings or a specific mapping for the containerps          List containerspull        Pull an image or a repository from a registrypush        Push an image or a repository to a registryrename      Rename a containerrestart     Restart one or more containersrm          Remove one or more containersrmi         Remove one or more imagesrun         Run a command in a new containersave        Save one or more images to a tar archive (streamed to STDOUT by default)search      Search the Docker Hub for imagesstart       Start one or more stopped containersstats       Display a live stream of container(s) resource usage statisticsstop        Stop one or more running containerstag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGEtop         Display the running processes of a containerunpause     Unpause all processes within one or more containersupdate      Update configuration of one or more containersversion     Show the Docker version informationwait        Block until one or more containers stop, then print their exit codesRun '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 -aCONTAINER ID   IMAGE         COMMAND    CREATED         STATUS                     PORTS     NAMESb6812c2d3cee   ubuntu        "bash"     4 minutes ago   Exited (0) 3 minutes ago             youthful_faraday99f729ea477b   hello-world   "/hello"   2 hours ago     Exited (0) 2 hours ago               xenodochial_noether2a1a3ae27a97   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+ COMMAND1 root      20   0    5960   1704   1276 R   0.0   0.1   0:00.05 toptop - 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+ COMMAND1 root      20   0    5960   1704   1276 R   0.0   0.1   0:00.05 toptop - 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+ COMMAND1 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
    2a1a3ae27a97e03fc773ef2c01d34a697d607c0b2639581cd7ae0546315d0f07Total reclaimed space: 34B[root@localhost mydock]# docker volume prune -f
    Deleted Volumes:
    5274edde97e9c2df7a46b7889626a3687d992eec31624b4b309d9b788400ba36Total 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.7command: --default-authentication-plugin=mysql_native_passwordrestart: alwaysenvironment:MYSQL_ROOT_PASSWORD: 19970805adminer:image: adminerrestart: alwaysports:- 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 bashroot@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... Doneroot@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 1500inet 172.17.0.3  netmask 255.255.0.0  broadcast 172.17.255.255ether 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 0TX packets 7206  bytes 395732 (395.7 KB)TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536inet 127.0.0.1  netmask 255.0.0.0loop  txqueuelen 1000  (Local Loopback)RX packets 0  bytes 0 (0.0 B)RX errors 0  dropped 0  overruns 0  frame 0TX packets 0  bytes 0 (0.0 B)TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0root@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清華源

總結

以上是生活随笔為你收集整理的Docker的安装、镜像源更换与简单应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。