---
# System prepended metadata

title: docker學習
tags: [RD5]

---

# docker學習

###### tags: `RD5`
* docker概述
* docker安裝
* docker命令
  * 容器命令
  * 鏡像命令
  * 操作命令
* docker鏡像
* 容器數據券

# docker 概述
傳統：開發jar，運維來做
現在：開發打包部署上線，一套流程做完！

java --- jar(環境) ---打包項目帶上環境(鏡像) ---(docker倉庫：商店) ---下載我們發佈的鏡像 ---直接運行即可！

docker給以上的問題提出了解決方案

docker思想就來自於集裝箱

jre --多個應用(端口衝突) --原來都是交叉的
隔離：docker核心思想 打包裝箱 每個箱子都是互相隔離的

docker 通過隔離機制 可以將服務器利用到極致

在容器技術出現之前 都是使用虛擬機技術

虛擬機也是屬於虛擬化技術 docker容器技術也是一種虛擬化技術

虛擬機技術缺點
1. 資源佔用多
2. 設定步驟多
3. 啟動慢
![](https://i.imgur.com/m2he2N0.png)


容器化技術
![](https://i.imgur.com/JWORbz5.png)

docker vs 虛擬機
* 傳統虛擬機 虛擬出一條硬件 運行一個完整的操作系統 然後在這個系統上安裝和運行軟件
* 容器內的應用直接運行在 宿主機的內容 容器是沒有自己的內核 也沒有虛擬硬件 所以輕便
* 每個容器間相互隔離 每個容器都有一個屬於自己的文件系統 互不影響

 
 ## devops
**應用更快速的交付和部署**
 傳統：一堆幫助文檔，安裝程序
 docker：打包鏡像發布測試，一鍵運行
 
**更便捷的升級和擴縮容**
使用了docker之後，我們部署應用就和搭積木一樣
項目打包為一個鏡像 擴展 服務器A 服務器Ｂ

**更簡單的系統運維**
在容器化之後 我們的開發 測試環境都高度一致

**更高效的計算資源利用**
docker是內核級別的虛擬化 可以在一個電腦上運行很多的容器實例 服務器性能最大化
 
 ## docker 基本組成
 ![](https://i.imgur.com/sJNCoh8.png)
**鏡像(image):**
docker鏡像就好比是一個模板，可以通過這個模板來創建容器服務 tomcat鏡像===>run==>tomcat01容器(提供服務器)，通過這個鏡像可以創建多個容器(最終服務運行或者項目運行就是在容器中)
**容器(container):**
docker利用容器技術 獨立運行一個或者一個組應用 通過鏡像來創建的
啟動 停止 刪除 基本命令
目前就可以把這個容器理解為就是一個簡易的linux系統
**倉庫(repository):**
存放鏡像的地方
倉庫分為公有倉庫和私有倉庫
docker hub

容器=啟動後的鏡像
鏡像就是安裝包 容器就是已安裝的app
遊戲光碟=鏡像 裝好後就是容器
可以簡單理解為安裝包和軟件的關西
## docker run流程圖
![](https://i.imgur.com/Ku1h964.png)

## 底層原理
**docker工作原理**

docker 是一個client - server 結構系統 docker的守護進程運行在主機上 通過socket從客戶端訪問
dockerserver接收到docker-client的指令 就會執行這個命令

![](https://i.imgur.com/MH4BZpp.png)

**docker為什麼比vm快**

## docker 常用命令
### 幫助命令
```shell
docker version    # 顯示docker的版本信息
docker info       # 顯示docker的系統信息，包括鏡像和容器的數量
docker 命令 --help # 幫助命令
```

### 鏡像命令
**docker images** 查看所有本地主機上的鏡像
```shell
tangrendeiPro:~ mrtang3838$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              bf756fb1ae65        8 months ago        13.3kB

# 解釋
REPOSITORY  鏡像倉庫源
TAG         鏡像標籤
IMAGE ID    鏡像id
CREATED     鏡像創建時間
SIZE        鏡像大小

# 可選項
    -a, --all        # 列出所有鏡像
    -q, --quiet      # 只顯示鏡像id
    
```
**docker search 搜索鏡像**
```shell
tangrendeiPro:~ mrtang3838$ docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   9958                [OK]                
mariadb                           MariaDB is a community-developed fork of MyS…   3642                [OK]                

# 可選項,通過搜索來過濾
--filter=stars=3000    # 搜索出來的鏡像就是stars大於3000的
tangrendeiPro:~ mrtang3838$ docker search mysql --filter=stars=3000
NAME                DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql               MySQL is a widely used, open-source relation…   9958                [OK]                
mariadb             MariaDB is a community-developed fork of MyS…   3642                [OK]   

```

**docker pull 下載鏡像**
```shell
# 下載鏡像 docker pull 鏡像名[:tag]
tangrendeiPro:~ mrtang3838$ docker pull mysql
Using default tag: latest    # 如果不寫 tag,默認就是 latest
latest: Pulling from library/mysql
d121f8d1c412: Pull complete     # 分層下載, docker image的核心 聯合文件系統
f3cebc0b4691: Pull complete 
1862755a0b37: Pull complete 
489b44f3dbb4: Pull complete 
690874f836db: Pull complete 
baa8be383ffb: Pull complete 
55356608b4ac: Pull complete 
dd35ceccb6eb: Pull complete 
429b35712b19: Pull complete 
162d8291095c: Pull complete 
5e500ef7181b: Pull complete 
af7528e958b6: Pull complete 
Digest: sha256:e1bfe11693ed2052cb3b4e5fa356c65381129e87e38551c6cd6ec532ebe0e808    # 簽名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest    # 真實地址


# 等價於他
docker pull mysql
docker pull docker.io/library/mysql:latest

# 指定版本下載
tangrendeiPro:~ mrtang3838$ docker pull mysql:5.7
5.7: Pulling from library/mysql
d121f8d1c412: Already exists     # 可共存 可想成是git的歷史版本 不衝突
f3cebc0b4691: Already exists 
1862755a0b37: Already exists 
489b44f3dbb4: Already exists 
690874f836db: Already exists 
baa8be383ffb: Already exists 
55356608b4ac: Already exists 
277d8f888368: Pull complete 
21f2da6feb67: Pull complete 
2c98f818bcb9: Pull complete 
031b0a770162: Pull complete 
Digest: sha256:14fd47ec8724954b63d1a236d2299b8da25c9bbb8eacc739bb88038d82da4919
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
```

**docker rmi 刪除鏡像**
```shell
tangrendeiPro:~ mrtang3838$ docker rmi -f 容器id    # 刪除指定的容器
tangrendeiPro:~ mrtang3838$ docker rmi -f 容器id 容器id 容器id    # 刪除多個容器
tangrendeiPro:~ mrtang3838$ docker rmi -f $(docker images -aq)    # 刪除全部的容器
```
### 容器命令
**說明：我們有了鏡像才可以創建容器**

ex:下載centos
```shell
docker pull centos
```
**新建容器並啟動**
```shell
docker run [可選參數] image

# 參數說明
--name="Name"    容器名字  tomcat01  tomcat02, 用來區分容器
-d               後台方式運行
-it              使用交互方式運行,進入容器查看內容
-p               指定容器的端口  -p  8080:8080
    -p ip:主機端口：容器端口
    -p 主機端口:容器端口  (常用)
    -p 容器端口
    容器端口
-p            隨機指定端口    

# 測試,啟動並進入容器
AlaniMac-Pro:~ mrtang3838$ docker run -it centos /bin/bash
[root@0d7b2ebb856a /]# ls    #查看容器內的centos,基礎版本 root後面的0d7b是centos的id
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

# 從容器內退回主機
[root@0d7b2ebb856a /]# exit
exit
AlaniMac-Pro:~ mrtang3838$
```
**列出所有運行中的容器**
```shell
# docker ps 命令
    # 列出當前正在運行的容器
-a  # 列出當前正在運行的容器+帶出歷史運行過的容器
-n=?    # 顯示最近創建的容器
-q  #只顯示容器編號

AlaniMac-Pro:~ mrtang3838$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
AlaniMac-Pro:~ mrtang3838$ docker ps -a
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS                          PORTS               NAMES
0d7b2ebb856a        centos              "/bin/bash"           4 minutes ago       Exited (0) About a minute ago                       hopeful_leakey
d179e798eec9        centos              "/bin/bash"           7 minutes ago       Exited (0) 4 minutes ago                            agitated_yalow
369e3f7e24f0        centos              "/Users/mrtang3838"   7 minutes ago       Created                                             magical_wu
b59d6f8a02c1        bf756fb1ae65        "/hello"              4 hours ago         Exited (0) 4 hours ago                              quizzical_proskuriakova
AlaniMac-Pro:~ mrtang3838$ docker ps -a -n=1
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
0d7b2ebb856a        centos              "/bin/bash"         6 minutes ago       Exited (0) 3 minutes ago                       hopeful_leakey
```
**退出容器**
```shell
exit    # 直接從容器停止並退出
Ctrl + P + Q    # 容器不停止退出
```
**刪除容器**
```shell
docker rm 容器id    # 刪除指定的容器
docker rm -f $(docker ps -aq)  #(刪除所有的容器)查出所有容器id並遞歸刪除
docker ps -a -q|xargs docker rm #刪除所有的容器
```
**啟動和停止容器的操作**
```shell
docker start 容器id    # 啟動容器
docer restart 容器id   # 重啟容器
docker stop 容器id     # 停止當前正在運行的容器
docker kill 容器id     # 強制停止當前容器
```

### 常用其他命令
**後台啟動容器**
```shell
# 命令 docker run -d 鏡像名
AlaniMac-Pro:~ mrtang3838$ docker run -d centos

# 問題docker ps, 發現 centos 停止了

# 常見的坑：docker 容器使用後台運行,就必須要有一個前台進程,docker發現沒有應用,就會自動停止
# nginx, 容器啟動後,發現自己沒有提供服務,就會立刻停止,就是沒有程序了
```
**查看日誌**
```shell
docker logs -f -t --tail 要查看的日誌數 容器id

# 顯示日誌
-tf    # 顯示日誌
--tail number # 要顯示日誌條數
AlaniMac-Pro:~ mrtang3838$ docker logs -tf --tail 10 dce7b86171bf
```
**查看容器中進程信息**
```shell
# 命令 docker top 容器id
AlaniMac-Pro:~ mrtang3838$ docker top 59c856f8d486
PID                 USER                TIME                COMMAND
2542                root                0:00                /bin/bash
```
**查看鏡像的元數據**
```shell
# 命令
docker inspect 容器id

# 測試
AlaniMac-Pro:~ mrtang3838$ docker inspect 59c856f8d486
[
    {
        "Id": "59c856f8d4864f7eeef779d9ef29b4adab4da702f1fb9ee1d5d3a1afa3e58277",
        "Created": "2020-09-13T14:01:28.785236983Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 2542,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-09-13T14:01:29.047764443Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
        "ResolvConfPath": "/var/lib/docker/containers/59c856f8d4864f7eeef779d9ef29b4adab4da702f1fb9ee1d5d3a1afa3e58277/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/59c856f8d4864f7eeef779d9ef29b4adab4da702f1fb9ee1d5d3a1afa3e58277/hostname",
        "HostsPath": "/var/lib/docker/containers/59c856f8d4864f7eeef779d9ef29b4adab4da702f1fb9ee1d5d3a1afa3e58277/hosts",
        "LogPath": "/var/lib/docker/containers/59c856f8d4864f7eeef779d9ef29b4adab4da702f1fb9ee1d5d3a1afa3e58277/59c856f8d4864f7eeef779d9ef29b4adab4da702f1fb9ee1d5d3a1afa3e58277-json.log",
        "Name": "/loving_bohr",
        "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,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/251b0e3576f3c67baff07a13e6ad3e7e348e50297d36acc531f5bb78585f1347-init/diff:/var/lib/docker/overlay2/407114731b002a8d080ac00a1b070d3982a04101de9bfc99836212671dd1df95/diff",
                "MergedDir": "/var/lib/docker/overlay2/251b0e3576f3c67baff07a13e6ad3e7e348e50297d36acc531f5bb78585f1347/merged",
                "UpperDir": "/var/lib/docker/overlay2/251b0e3576f3c67baff07a13e6ad3e7e348e50297d36acc531f5bb78585f1347/diff",
                "WorkDir": "/var/lib/docker/overlay2/251b0e3576f3c67baff07a13e6ad3e7e348e50297d36acc531f5bb78585f1347/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "59c856f8d486",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20200809",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "50e7e4004f3677104177b67379a4533a76a1e9877075ced84e79e016264c5834",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/50e7e4004f36",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "362d897ad1aa4be95b155df389f69a823b4c19f024c98b749a51daf945d4c586",
            "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": "4528f6449b63918c0c2211fb26ed48659db66caf9c9ebe0b9b83c3d3a694abcb",
                    "EndpointID": "362d897ad1aa4be95b155df389f69a823b4c19f024c98b749a51daf945d4c586",
                    "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
                }
            }
        }
    }
]
```
**進入當前正在運行的容器**
```shell
# 我們通常容器都是使用後台方式運行的,需要進入容器,修改一些配置

# 命令
$ docker exec -it 容器id bashShell 
```

