Docker。

lyfGeek發表於2020-09-25

Docker。



概述。

Docker 為什麼出現。

一款產品,開發 ~ 上線,兩套環境。

“我在我的電腦上可以執行!”。

環境配置十分麻煩,每一臺機器都要部署環境(叢集 Redis、ES、Hadoop)。費時費力。

傳統:開發 jar,運維來作。
現在:開發打包部署上線,一套流程做完。

java ~ apk ~ 釋出(應用商店)~ 張三使用 apk ~ 安裝即可用。
java ~ jar(+環境)~ 打包專案帶上環境(映象)~(Docker 倉庫:商店)~下載我們釋出的映象 ~ 直接執行即可。

Docker 的思想來自於集裝箱。


Docker 歷史。

2010 年,幾個年輕人,在美國成立了一家公司 DotCloud。做一些 PASS 雲端計算服務,Linux 的有關的容器技術。他們將自己的技術(容器化技術)命名 Docker

Docker 剛蛋生的時候,沒有引起行業注意。

↓ ↓ ↓

2013 開源。

2014 年 9 月, Docker 1.0 釋出。

在容器技術出來之前,虛擬機器技術。
虛擬機器:在 Windows 裝一個 VMWare,要虛擬一臺電腦,笨重。
Docker:隔離,映象(最核心的環境 4M + jdk + MySQL)十分小巧,執行映象即可。


文件:https://docs.docker.com/

倉庫:https://www.docker.com/products/docker-hub

Docker 能做什麼。

  • 虛擬機器技術。

資源佔用多。
冗餘步驟多。
啟動慢。

在這裡插入圖片描述

  • 容器化技術。

在這裡插入圖片描述

  • DevOps(開發、運維)。
  • 應用更快速的交付和部署。
    傳統:一堆幫助文件,安裝程式。
    Docker:打包映象釋出測試,一鍵執行。
  • 更便捷的升級和擴縮容。
    Docker 部署應用就像搭積木一樣,專案打包為一個映象。
  • 更簡單的系統運維。
    開發、測試環境高度一致。
  • 更高效的計算資源。
    Docker 是核心級別的虛擬化,可以在一個物理機上執行很多容器例項。伺服器的效能可以被壓榨到極致。

Docker 基本組成。

在這裡插入圖片描述

  • 映象 image。
    Docker 映象就好比一個模板,可以通過這個模板來建立容器服務,Tomcat 映象 --> run --> tomcat01容器(提供伺服器),通過這個映象可以建立多個容器(最終服務執行或專案執行就是在容器中)。
  • 容器 container。
    Docker 利用容器技術,獨立執行一個或一個組應用,通過映象來建立的。可以理解為一個簡易的 Linux 系統。
  • 倉庫 repository。
    倉庫就是存放映象的地方。
    倉庫分為共有倉庫和私有倉庫。
    Docker Hub(預設,國外的)。
    阿里雲,華為雲都有容器伺服器。配置映象加速。

Docker 安裝。

https://docs.docker.com/engine/install/centos/

CentOS 7 安裝 Docker~並更換國內源。

[geek@192 tools_my]$ sudo docker run hello-world

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/



Docker 解除安裝。

Uninstall Docker Engine

Uninstall the Docker Engine, CLI, and Containerd packages:

$ sudo yum remove docker-ce docker-ce-cli containerd.io

Images, containers, volumes, or customized configuration files on your host are not automatically removed. To delete all images, containers, and volumes:

$ sudo rm -rf /var/lib/docker

You must delete any edited configuration files manually.


阿里雲映象加速。

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://********.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

底層原理。

Docker 是一個 Client - Server 結構的系統,Docker 的守護程式執行在主機上,通過 Socket 從客戶端訪問。

Docker Server 接收到 Docker Client 的指令,就會執行這個命令。

在這裡插入圖片描述

  • Docker 為什麼比虛擬機器快?

Docker 有著比虛擬機器更少的抽象層。
Docker 利用的是宿主機的核心,vm 需要是 Guest OS。

所以說,新建一個容器的時候,Docker 不需要像虛擬機器一樣重新載入一個作業系統的核心,避免引導。虛擬機器是載入 Guest OS,分鐘級別的,而 Docker 是利用宿主機的作業系統,省略了這個複雜的過程。


常用命令。

幫助命令。

docker version # 顯示 Docker 的版本資訊。
docker info # 顯示 Docker 的系統資訊,包括映象和容器的數量。
docker 命令 --help # 幫助命令。

[geek@192 ~]$ sudo docker
[sudo] password for geek: 

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:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  engine      Manage the docker engine
  image       Manage images
  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.

https://docs.docker.com/engine/reference/run/


映象命令。
docker images。

顯示本地所有映象。

[geek@192 ~]$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7.29              413be204e9c3        4 months ago        456MB
hello-world         latest              fce289e99eb9        20 months ago       1.84kB

REPOSITORY
TAG
IMAGE ID
CREATED
SIZE

Name, shorthandDefault Description
–all , -aShow all images (default hides intermediate images)
–digestsShow digests
–filter , -fFilter output based on conditions provided
–formatPretty-print images using a Go template
–no-truncDon’t truncate output
–quiet , -qOnly show numeric IDs

docker search。

搜尋映象。

docker search [OPTIONS] TERM
Extended description
Search Docker Hub for images

For example uses of this command, refer to the examples section below.

Options

Name, shorthandDefaultDescription
–automated (deprecated)Only show automated builds
–filter, -fFilter output based on conditions provided
–formatPretty-print search using a Go template
–limit25Max number of search results
–no-truncDon’t truncate output
–stars , -s(deprecated)Only displays with at least x stars

docker pull

下載映象。

docker pull [OPTIONS] NAME[:TAG|@DIGEST]

[geek@192 ~]$ sudo docker pull mysql
Using default tag: latest  # 如果不寫 tag,預設下載最新版本 latest。
latest: Pulling from library/mysql
d121f8d1c412: Pulling fs layer  # 分層下載。docker image 的核心,聯合檔案系統。

[geek@192 ~]$ sudo docker pull mysql:5.7.29
5.7.29: Pulling from library/mysql
54fec2fa59d0: Already exists   # 分層下載。docker image 的核心,聯合檔案系統。
bcc6c6145912: Already exists 
951c3d959c9d: Already exists 
05de4d0e206e: Pull complete 
319f0394ef42: Pull complete 
d9185034607b: Pull complete 
013a9c64dadc: Pull complete 
58b7b840ebff: Pull complete 
9b85c0abc43d: Pull complete 
bdf022f63e85: Pull complete 
35f7f707ce83: Pull complete 
Digest: sha256:95b4bc7c1b111906fdb7a39cd990dd99f21c594722735d059769b80312eb57a7
Status: Downloaded newer image for mysql:5.7.29
docker.io/library/mysql:5.7.29


docker rmi。

刪除映象。

Name, shorthandDefaultDescription
–force , -fForce removal of the image
–no-pruneDo not delete untagged parents

docker rmi -f 映象 id # 刪除指定的映象。
docker rmi -f 映象 id 映象 id 映象 id # 刪除多個映象。
docker rmi -f $(docker images -aq) # 刪除全部映象。


容器命令。

有了映象才可以建立容器。

docker pull centos

docker run --help
docker run [可選引數] image
–name=“容器名”
-d ~ 後臺方式執行。
-it ~ 使用互動方式執行,進入容器檢視內容。
-p ~ 指定容器埠。
 -p ip:主機埠:容器埠。
 -p 主機埠:容器埠。(常用)。
 -p 容器埠(不需要外部訪問,容器內部埠)。
 容器埠。
-P ~ 隨機埠。


列出所有執行的容器。

docker ps


列出所有的容器。

docker ps -a

-n=? # 列出最近建立的容器。
-q # 只顯示容器的編號。


退出容器。

exit # 容器停止並退出。
Ctrl + P + Q # 容器不停止退出。


刪除容器。

docker rm 容器 id。
docker rm -f $(docker ps -aq)
docker ps -a -q | xargs docker rm


啟動和停止容器。

docker start 容器 id。
docker stop 容器 id。
docker restart 容器 id。
docker kill 容器 id。 # 強制。


其他常用命令。
後臺啟動容器。
docker run -d centos

// 問題。docker ps 發現 centos 停止了。

Docker 容器使用後臺執行,就必須要有一個前臺程式。docker 發現沒有前臺應用,就會自動停止該容器。

eg. Nginx。


檢視日誌。
[geek@192 ~]$ sudo docker logs --help
[sudo] password for geek: 

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for
                       42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m
                       for 42 minutes)

docker logs -tf -tail 10 容器 id。


容器中的程式資訊 ~ top。

docker top 容器 id。

[geek@192 ~]$ sudo docker top be45da4c5b93
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
polkitd             7501                7486                0                   22:33               ?                   00:00:01            mysqld

docker inspect。容器後設資料。
[geek@192 ~]$ sudo docker inspect --help

Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type

[geek@192 ~]$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
be45da4c5b93        413be204e9c3        "docker-entrypoint.s…"   4 months ago        Up 29 minutes       33060/tcp, 0.0.0.0:3307->3306/tcp   mysql_geek
[geek@192 ~]$ sudo docker inspect be45da4c5b93
[
    {
        "Id": "be45da4c5b93d8d82753dce660fdbf0184c117bdf72d9ee856665f481f623877",
        "Created": "2020-04-06T22:15:58.597019498Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "mysqld"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 7501,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-08-27T14:33:34.678287048Z",
            "FinishedAt": "2020-08-27T14:00:12.753590425Z"
        },
        "Image": "sha256:413be204e9c34f31476a0680b6521873fb519c749693b181228ff47492a7fe3b",
        "ResolvConfPath": "/var/lib/docker/containers/be45da4c5b93d8d82753dce660fdbf0184c117bdf72d9ee856665f481f623877/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/be45da4c5b93d8d82753dce660fdbf0184c117bdf72d9ee856665f481f623877/hostname",
        "HostsPath": "/var/lib/docker/containers/be45da4c5b93d8d82753dce660fdbf0184c117bdf72d9ee856665f481f623877/hosts",
        "LogPath": "/var/lib/docker/containers/be45da4c5b93d8d82753dce660fdbf0184c117bdf72d9ee856665f481f623877/be45da4c5b93d8d82753dce660fdbf0184c117bdf72d9ee856665f481f623877-json.log",
        "Name": "/mysql_geek",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "3306/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "3307"
                    }
                ]
            },
            "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/b0db5ee46558d330232ea016336067d1890a948c10a74c5fbcc95ce84809c9b6-init/diff:/var/lib/docker/overlay2/34435b08289bb58d920e294bdc084abb5e7bd8ca6eeeebeac585aa3d58bd1745/diff:/var/lib/docker/overlay2/a956e638e9365fa896fcacfa4819aa45b5126f6f774a33f1b4c22fb8915ea759/diff:/var/lib/docker/overlay2/c9cf19bd7db463e098c5c31c26b6709b78d7482116fc4239a3dcd66b277c8026/diff:/var/lib/docker/overlay2/19454098e97f64a4edc53cd3f5cef4e0ba0d2145a7927845586f2fd209ddaa1a/diff:/var/lib/docker/overlay2/9529736c0acd4d18a5a6540b8af98b2dcf9368948af7121850dd5f693c10a06b/diff:/var/lib/docker/overlay2/8cb480298f4e7d3f54b3ed365fb222e73e2a47b7128dcfc7902952569497a6a3/diff:/var/lib/docker/overlay2/7550a0aad73c643bca6a01239c3709aead185080b909bd7dab9257e5f3f0dfa8/diff:/var/lib/docker/overlay2/998e4a5bc1d6e6a124e25cb69155283da2cdf0472284bac785839be224a62d10/diff:/var/lib/docker/overlay2/49948aaa148f15b67fb990a88ee8aa1c36a311f5b45f3988fcad734a55e11475/diff:/var/lib/docker/overlay2/2462775172a6a17f6e925bb15e47c25c99bb785a83f56ff22e2afba745a024f9/diff:/var/lib/docker/overlay2/d00eb80fb1c1d284d5054c36176f3459e737194cf9b01af83fa2f150ef7b5141/diff",
                "MergedDir": "/var/lib/docker/overlay2/b0db5ee46558d330232ea016336067d1890a948c10a74c5fbcc95ce84809c9b6/merged",
                "UpperDir": "/var/lib/docker/overlay2/b0db5ee46558d330232ea016336067d1890a948c10a74c5fbcc95ce84809c9b6/diff",
                "WorkDir": "/var/lib/docker/overlay2/b0db5ee46558d330232ea016336067d1890a948c10a74c5fbcc95ce84809c9b6/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "c7f8b6a9062ee284710b8d3f60eab7ce5da5642f5ca5c1500ece8dd0f2473559",
                "Source": "/var/lib/docker/volumes/c7f8b6a9062ee284710b8d3f60eab7ce5da5642f5ca5c1500ece8dd0f2473559/_data",
                "Destination": "/var/lib/mysql",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "be45da4c5b93",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "3306/tcp": {},
                "33060/tcp": {}
            },
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "MYSQL_ROOT_PASSWORD=root",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.7",
                "MYSQL_MAJOR=5.7",
                "MYSQL_VERSION=5.7.29-1debian10"
            ],
            "Cmd": [
                "mysqld"
            ],
            "Image": "mysql:5.7.29",
            "Volumes": {
                "/var/lib/mysql": {}
            },
            "WorkingDir": "",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "22742b719119538aa2cbe6996586f06fa966624f7017a68041b5fc3b01688e5a",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3307"
                    }
                ],
                "33060/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/22742b719119",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "57d39a8070c00926eb6b93160f6929240f452e60b099f9875dd5f8c3de3e3747",
            "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": "38931101b374d0d8b7ff824e014421b6205795b47203d791b5f38c59d3e3cdc9",
                    "EndpointID": "57d39a8070c00926eb6b93160f6929240f452e60b099f9875dd5f8c3de3e3747",
                    "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
                }
            }
        }
    }
]


進入當前正在執行的容器。docker exec / attach。

docker exec -it 容器 id /bin/bash

docker attach 容器 id。
// # 正在執行的程式碼。。。

docker exec # 進入容器後開啟一個新的終端。
docker attach # 進入容器正在執行的終端。

相關文章