1. 程式人生 > 其它 >Docker 安裝及基本命令

Docker 安裝及基本命令

Docker官方文件

官方文件:

Docker遠端倉庫

安裝步驟以及命令

準備工作

# 1. 解除安裝已安裝過的舊版本的docker [新伺服器無需此操作]
yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
# 2. 需要安裝的包
yum install -y  yum-utils

開始docker安裝命令

# 3. 設定映象倉庫
# 官方映象地址是比較慢,可以使用國內的,比如阿里的
yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
    
#推薦使用國內的
yum-config-manager \
    --add-repo \
    https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
# 4. 更新yum索引,獲取最新的索引yum makecache fast
yum makecache fast

# 5. 安裝docker相關的 docker-ce 社群版 而ee是企業版,企業版是收費
yum install docker-ce docker-ce-cli containerd.io

# 6.啟動docker
systemctl start docker 

# 7. 驗證是否安裝成功
docker version 

驗證安裝成功

執行version命令,出現docker的版本資訊,即為安裝成功

Hollo-world

Hollo-word示例

測試docker環境是否正常,使用官方提供的hollo-word的示例

映象執行命令

docker run hello-world # docker run  映象  

執行結果:

  1. 當執行run命令時,本地不存在需要執行的映象,則會到遠端映象倉庫拉取

  2. 執行映象為新增tag版本號,則會拉取遠端最新的映象版本 lastest 表示最新版本

映象基本命令

  • 容器啟動命令
docker run [可選引數] image | docker container run [可選引數] image 
#參書說明
--name="Name"		#容器名字 tomcat01 tomcat02 用來區分容器
-d					#後臺方式執行
-it 				#使用互動方式執行,進入容器檢視內容
-p					#指定容器的埠 -p 8080(宿主機):8080(容器)
		-p ip:主機埠:容器埠
		-p 主機埠:容器埠(常用)
		-p 容器埠
		容器埠
-P(大寫) 				隨機指定埠

# 測試、啟動並進入容器
[root@iz2zeak7sgj6i7hrb2g
[root@iz2zeak7sgj6i7hrb2g862z ~]# docker run -it centos /bin/bash 【啟動並進入容器】
[root@241b5abce65e /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@241b5abce65e /]# exit 【從容器退回主機】
exit

常見的坑:docker容器使用後臺執行,就必須要有要一個前臺程序,docker發現沒有應用,就會自動停止

  • 檢視當前docker環境下的所有映象
docker images #檢視當前docker環境下的所有映象
docker image ls

[root@bogon /]# docker images
# 映象名稱      映象版本    唯一ID           時間         映象大小
 REPOSITORY    TAG       IMAGE ID       CREATED       SIZE
 hello-world   latest    feb5d9fea6a5   6 weeks ago   13.3kB

  • 搜尋映象 【建議少用,使用遠端倉庫可以檢視映象詳情】
docker search #搜尋映象
  • 下載映象
docker pull #下載映象 docker image pull

  • 刪除映象
docker rmi #刪除映象 docker image rm
docker rmi -f $(docker images -aq) #刪除全部的映象

容器基本命令

  • 查詢容器
docker ps # 列出當前正在執行的容器
  -a, --all     	 #列出當前正在執行的容器 + 帶出歷史執行過的容器
  -n=?, --last int   #列出最近建立的?個容器 ?為1則只列出最近建立的一個容器,為2則列出2個
  -q, --quiet        #只列出容器的編號

[root@bogon /]# docker ps
# 容器唯一ID	映象名		執行命令				   時間			 狀態           暴露埠	  容器名
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
7d18e99366ff   nginx     "/docker-entrypoint.…"   2 minutes ago   Up 2 minutes   80/tcp    pedantic_faraday
--------
[root@bogon /]# docker ps -a
CONTAINER ID   IMAGE         COMMAND                  CREATED          STATUS                      PORTS     NAMES
7d18e99366ff   nginx         "/docker-entrypoint.…"   4 minutes ago    Up 4 minutes                80/tcp    pedantic_faraday【正在執行的容器】
d05f3bc3884a   hello-world   "/hello"                 45 minutes ago   Exited (0) 45 minutes ago             modest_tereshkova【之前執行過的容器】
--------
[root@bogon /]# docker ps -q
d9b9a2b10c76
3c4c5037f3d4
--------
[root@bogon /]# docker ps -n=2
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
d9b9a2b10c76   nginx     "/docker-entrypoint.…"   36 seconds ago   Up 35 seconds   80/tcp    nginx06
3c4c5037f3d4   nginx     "/docker-entrypoint.…"   41 seconds ago   Up 40 seconds   80/tcp    nginx05

  • 容器停止命令
docker stop 容器ID  # 容器停止命令

# 查詢到正在執行的容器,
# -q  僅展示容器ID
[root@bogon /]# docker ps -q
cca290da9e9c
[root@bogon /]# docker stop cca290da9e9c
cca290da9e9c 【容器停止成功】

docker stop $(docker ps -aq)  # 停止所有正在執行的容器  $ 代表取值
[root@bogon /]# docker ps -q 【正在執行的容器】
a924fd191505
7d58cbf29ea3
[root@bogon /]# docker stop $(docker ps -q)【停止所有正在執行的容器】
a924fd191505
7d58cbf29ea3

  • 殺死正在執行的容器
docker kill 容器ID 
  • 刪除容器
docker rm 容器id   				#刪除指定的容器,不能刪除正在執行的容器,如果要強制刪除 rm -rf
docker rm -f $(docker ps -aq)  	 #刪除所有的容器
  • 啟動和重啟容器
docker start 容器id	#啟動容器
docker restart 容器id	#重啟容器
  • 進入容器
 docker exec -it 容器ID /bin/bash  #進入容器並且開啟一個新的終端
docker attach 容器id #進入容器並且進入正在執行的終端
  • 退出容器
exit 		#容器直接退出
ctrl +P +Q  #容器不停止退出 	---注意:這個很有用的操作
  • 檢視docker日誌
docker logs --help
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 run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done" #模擬日誌      
#顯示日誌
-tf		#顯示日誌資訊(一直更新)
--tail number #需要顯示日誌條數
docker logs -t --tail n 容器id #檢視n行日誌
docker logs -ft 容器id #跟著日誌

  • 檢視容器中程序資訊
docker top 容器ID
  • 檢視容器的元資料
#命令
docker inspect 容器ID 

# 測試
[root@bogon /]# docker inspect  7daa2237ec1d
[
    {
        "Id": "7daa2237ec1d92b8b4b850814e9c74bef8e48efc978aed7234c979594c88d07a",
        "Created": "2021-11-08T08:23:50.342564917Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 84968,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-11-08T08:23:51.070809271Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:87a94228f133e2da99cb16d653cd1373c5b4e8689956386c1c12b60a20421a02",
        "ResolvConfPath": "/var/lib/docker/containers/7daa2237ec1d92b8b4b850814e9c74bef8e48efc978aed7234c979594c88d07a/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/7daa2237ec1d92b8b4b850814e9c74bef8e48efc978aed7234c979594c88d07a/hostname",
        "HostsPath": "/var/lib/docker/containers/7daa2237ec1d92b8b4b850814e9c74bef8e48efc978aed7234c979594c88d07a/hosts",
        "LogPath": "/var/lib/docker/containers/7daa2237ec1d92b8b4b850814e9c74bef8e48efc978aed7234c979594c88d07a/7daa2237ec1d92b8b4b850814e9c74bef8e48efc978aed7234c979594c88d07a-json.log",
        "Name": "/nginx02",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": [
            "4120fe6eff388f1ca32d9c09cce02c286e500ea0aca00e596ba590adfeac6ca7",
            "ef7a9731d2bc08e70aef31905aba67028e8c85fa5e42ac0dc942dd9c03071cb4"
        ],
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "8000"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "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/0778d818ab0406f00a7ad651d9c70f1b586642fb92d468220a4b2d66ffdeecc6-init/diff:/var/lib/docker/overlay2/d58fab8d23dafafd6c7674ffac3dad8ed91b6515b413bdc128164d74482e63fd/diff:/var/lib/docker/overlay2/c7d9e2e744739c79e8ba575430ca0fb9e5cb5707309aaa3844ac4eec7800fd05/diff:/var/lib/docker/overlay2/bc03eef418af2d95e47e4a90db360d1195c84daada7133561f80384f366287bb/diff:/var/lib/docker/overlay2/4a0f6d30a8c3e58f8b01e2b5c964a7b4a9abc90a295cc74692ffc60ec6fbe125/diff:/var/lib/docker/overlay2/fb8c8d457fbd46f237da67fc31370d3449dd3104d872bdb888102e9c221ee44b/diff:/var/lib/docker/overlay2/efc57b47f664f34115950ea32175fcde004bf1c1fc758c6bdc39f45ae5abe13d/diff",
                "MergedDir": "/var/lib/docker/overlay2/0778d818ab0406f00a7ad651d9c70f1b586642fb92d468220a4b2d66ffdeecc6/merged",
                "UpperDir": "/var/lib/docker/overlay2/0778d818ab0406f00a7ad651d9c70f1b586642fb92d468220a4b2d66ffdeecc6/diff",
                "WorkDir": "/var/lib/docker/overlay2/0778d818ab0406f00a7ad651d9c70f1b586642fb92d468220a4b2d66ffdeecc6/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "7daa2237ec1d",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": true,
            "AttachStderr": true,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.3",
                "NJS_VERSION=0.6.2",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <[email protected]>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "de74adbe1f577f46455dac020aac4dd14c3bada9810ba35b06b710f0e0522374",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "8000"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "8000"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/de74adbe1f57",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "3ffd53ff1bf337358adfcf1fd9a969c8ddd212ca887d38d46c19a758dd64ea6c",
            "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": "eec222979fd743eb8682227b74092fa21437ae7c785033443db4dcae88d93352",
                    "EndpointID": "3ffd53ff1bf337358adfcf1fd9a969c8ddd212ca887d38d46c19a758dd64ea6c",
                    "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
                }
            }
        }
    }
]
[root@bogon /]# 
  • 從容器內拷貝到主機上
docker cp 容器id:容器內路徑  主機目的路徑

小結

命令集合

  attach      Attach local standard input, output, and error streams to a running container
  #當前shell下 attach連線指定執行的映象
  build       Build an image from a Dockerfile # 通過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 #檢視docker容器的變化
  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 #匯出容器檔案系統作為一個tar歸檔檔案[對應import]
  history     Show the history of an image # 展示一個映象形成歷史
  images      List images #列出系統當前的映象
  import      Import the contents from a tarball to create a filesystem image #從tar包中匯入內容建立一個檔案系統映象
  info        Display system-wide information # 顯示全系統資訊
  inspect     Return low-level information on Docker objects #檢視容器詳細資訊
  kill        Kill one or more running containers # kill指定docker容器
  load        Load an image from a tar archive or STDIN #從一個tar包或標準輸入中載入一個映象[對應save]
  login       Log in to a Docker registry # 登入遠端倉庫
  logout      Log out from a Docker registry # 退出遠端倉庫
  logs        Fetch the logs of a container # 檢視docker 日誌
  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 # 啟動docker
  stats       Display a live stream of container(s) resource usage statistics # 映象或docker 狀態
  stop        Stop one or more running containers # 停止容器/停止docker
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE # 映象tag版本
  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 # docker 版本
  wait        Block until one or more containers stop, then print their exit codes

其它

宿主機埠容器內部埠 以及埠暴露:

容器內nginx啟動後對外暴露埠號為80,宿主機通過-p命令將3344埠與容器的80埠對映

命令:

docker run -p 3344:80 映象名 # -p小寫為指定埠號的對映
-P # 大寫-P為宿主機任意埠號與容器暴露的埠號對映