docker筑基篇-01-docker基礎命令及常用選項

[TOC]

1 docker 基礎命令

info | version

# 查看docker總體信息
[root@h1 ~]# docker info
Containers: 1
Images: 42
Storage Driver: devicemapper
 Pool Name: docker-253:0-395232-pool
 Pool Blocksize: 65.54 kB
 Backing Filesystem: extfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 2.516 GB
 Data Space Total: 107.4 GB
 Data Space Available: 29.24 GB
 Metadata Space Used: 3.273 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.144 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.117-RHEL6 (2016-08-15)
Execution Driver: native-0.2
Logging Driver: json-file
Kernel Version: 2.6.32-642.6.1.el6.x86_64
Operating System: <unknown>
CPUs: 1
Total Memory: 1.818 GiB
Name: h1
ID: KEQG:W5MZ:K5D3:RQRU:UUCV:SMGZ:NNQZ:BKVI:SZUS:HFEV:FTA7:GAI7

# 版本信息
[root@h1 ~]# docker version
Client version: 1.7.1
Client API version: 1.19
Go version (client): go1.4.2
Git commit (client): 786b29d/1.7.1
OS/Arch (client): linux/amd64
Server version: 1.7.1
Server API version: 1.19
Go version (server): go1.4.2
Git commit (server): 786b29d/1.7.1
OS/Arch (server): linux/amd64

# 版本信息
[root@h1 ~]# docker -v
Docker version 1.7.1, build 786b29d/1.7.1

ps

列出所有的container。不帶參數的時候只是列出正在運行的container。

-a,--all
    列出所有的容器
-s,--size
    容器所占的空間大小
-l,--latest=true|false
    只列出最近創建的容器,包括非運行的容器

inspect

可以查看比ps更加底層的信息。

-f, --format=""
    利用go語言模板來格式化輸出

rm

刪除指定容器

-f,--force
    強制刪除,包括運行狀態的容器。
-v,--volume
    連帶刪除和容器關聯的volume,謹慎操作。

start | restart

啟動/重啟指定的容器

docker start container-name

stop

停止一個正在運行的container

-t, --time=10
    Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.

attach

可以連接到一個正在運行的container上。

[root@h1 ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5d54de7bd727        centos:6.8          "/bin/bash"         9 minutes ago       Up 22 seconds                           c1           
[root@h1 ~]# docker attach c1
[root@5d54de7bd727 /]#

logs

可以監控一個正在運行的容器的日志記錄

-f, --follow=true|false
    實時監控日志輸出. The default is false.
-t, --timestamps=true|false
    日志記錄中帶上時間戳. The default is false.
docker logs -ft c1

top

exec

在一個正在運行的容器上執行命令

-d, --detach=true|false
    在后臺執行命令. The default is false.
-i, --interactive=true|false
    執行交互式命令. The default is false
-u, --user=""
    指定該命令以哪個用戶的身份執行.

# 在名稱為daemon_dev的容器上以后臺任務的方式執行命令 "touch /etc/newfile"
docker exec -d daemon_dev touch /etc/newfile

# 在名稱為daemon_dev的容器上打開一個交互式終端
docker exec -t -i daemon_dev /bin/bash

2 run命令

該命令會在一個新的容器中啟動一個進程。該進程擁有自己的文件系統,網絡組件,進程樹等一個子系統應該具有的基礎設施。

常用選項

-i, --interactive=false
    容器的STDIN是否開啟
-t, --tty=false
    為容器分配一個偽tty終端
--name
    為容器指定一個名稱,名稱的命必須是唯一的??梢酝ㄟ^名稱來代替容器ID引用容器
-d, --detach=true|false
    Detached mode:run the container in the background and print the new container ID. 
    The default is false.
--restart=no|always|on-failure[:max-retry]
    設置container在退出的時候是否自動重啟,以及重啟的策略。
    no:不自動重啟
    always:總是自動重啟
    on-failure:在退出碼為非零的時候重啟,并可以指定max-retry表示最多嘗試重啟的次數。

示例一

[root@h1 ~]# docker run -i -t centos:6.8 /bin/bash
Unable to find image 'centos:6.8' locally
6.8: Pulling from centos
386c6db8c14f: Pull complete 
8986abc42d08: Pull complete 
80e46367f846: Pull complete 
80e46367f846: Pulling fs layer 
Digest: sha256:233cbc13832f97e83773d2e4a6f9f3a81959bc9b5c1b03135d6bbd67a9db8b66
Status: Downloaded newer image for centos:6.8
[root@ec5bfab76e40 /]# 

命令執行過程:

先本地查找是否存在鏡像centos:6.8。如果本地不存在,去默認的DockerHub查找下載并將其保存在本地。
然后利用該鏡像去創建一個新的容器。
當容器創建完成之后,就會執行我們傳遞給他的命令/bin/bash啟動一個shell??梢钥闯雒钐崾痉矎膔oot@h1變成了root@ec5bfab76e40。

之后就可以像使用一個真正的centos操作系統來使用它了。只是這個操作系統只提供了一些最基本的命令:

[root@ec5bfab76e40 /]# hostname 
ec5bfab76e40


[root@ec5bfab76e40 /]# cat /etc/hosts
172.17.0.1  ec5bfab76e40
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters


[root@ec5bfab76e40 /]# ifconfig 
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:01  
          inet addr:172.17.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:acff:fe11:1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:468 (468.0 b)  TX bytes:558 (558.0 b)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

此時,在該終端中執行exit或者通過其他方式退出終端(/bin/bash結束)。該容器就會停止運行。

示例二

docker run --name daemon_dev -d centos:6.8 /bin/sh -c "while true;do echo hello world;sleep 1;done"

啟動一個名稱為daemon_dev的容器,該容器在后臺運行,并一直打印hello world。

可以通過logs命令查看其日志。

[root@h1 ~]# docker logs -tf daemon_dev
2016-10-17T02:47:57.744262702Z hello world
2016-10-17T02:47:57.744262702Z hello world
2016-10-17T02:47:57.744262702Z hello world
2016-10-17T02:47:57.744262702Z hello world
2016-10-17T02:47:57.744262702Z hello world
2016-10-17T02:47:57.744262702Z hello world
2016-10-17T02:47:58.748041451Z hello world
2016-10-17T02:47:59.750740053Z hello world
# ……

利用exec執行命令:

[root@h1 ~]# docker exec -d daemon_dev touch /etc/newfile
[root@h1 ~]# docker exec -t -i daemon_dev /bin/bash
[root@833898befd96 /]# id
uid=0(root) gid=0(root) groups=0(root)
[root@833898befd96 /]# exit
exit
[root@h1 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS               NAMES
833898befd96        centos:6.8          "/bin/sh -c 'while t   8 minutes ago       Up 8 minutes                            daemon_dev

停止該container:

docker stop daemon_dev

示例三

docker run --restart=always --name daemon_dev -d centos:6.8 /bin/sh -c "while true;do echo hello world;sleep 1;done"

該示例的基本功能和示例二類似,只不過該容器會自動重啟。

查看更加詳細的內部信息:

[root@h1 ~]# docker inspect daemon_dev
[
{
    "Id": "efd88d4e01c380b5d70b0f96175e223b76cdc1be0b22697e08e8a58f786005cd",
    "Created": "2016-10-17T03:05:06.213822618Z",
    "Path": "/bin/sh",
    "Args": [
        "-c",
        "while true;do echo hello world;sleep 1;done"
    ],
    "State": {
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 7646,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2016-10-17T03:05:06.616292242Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "80e46367f84650bdda8e3e638ba61be232e9881a8159bfed6d42f914597c68f4",
    "NetworkSettings": {
        "Bridge": "",
        "EndpointID": "36b326748dd4914c72cb3b349aebeda4d2bd74f4a9fba497f02c8784f24c002d",
        "Gateway": "172.17.42.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "HairpinMode": false,
        "IPAddress": "172.17.0.12",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "MacAddress": "02:42:ac:11:00:0c",
        "NetworkID": "1839f9caada911ea3b980fde577641dabbef9b198b5da9850f686115753c293a",
        "PortMapping": null,
        "Ports": {},
        "SandboxKey": "/var/run/docker/netns/efd88d4e01c3",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null
    },
    "ResolvConfPath": "/var/lib/docker/containers/efd88d4e01c380b5d70b0f96175e223b76cdc1be0b22697e08e8a58f786005cd/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/efd88d4e01c380b5d70b0f96175e223b76cdc1be0b22697e08e8a58f786005cd/hostname",
    "HostsPath": "/var/lib/docker/containers/efd88d4e01c380b5d70b0f96175e223b76cdc1be0b22697e08e8a58f786005cd/hosts",
    "LogPath": "/var/lib/docker/containers/efd88d4e01c380b5d70b0f96175e223b76cdc1be0b22697e08e8a58f786005cd/efd88d4e01c380b5d70b0f961
75e223b76cdc1be0b22697e08e8a58f786005cd-json.log",    "Name": "/daemon_dev",
    "RestartCount": 0,
    "Driver": "devicemapper",
    "ExecDriver": "native-0.2",
    "MountLabel": "",
    "ProcessLabel": "",
    "Volumes": {},
    "VolumesRW": {},
    "AppArmorProfile": "",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LxcConf": [],
        "Memory": 0,
        "MemorySwap": 0,
        "CpuShares": 0,
        "CpuPeriod": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "CpuQuota": 0,
        "BlkioWeight": 0,
        "OomKillDisable": false,
        "Privileged": false,
        "PortBindings": {},
        "Links": null,
        "PublishAllPorts": false,
        "Dns": null,
        "DnsSearch": null,
        "ExtraHosts": null,
        "VolumesFrom": null,
        "Devices": [],
        "NetworkMode": "bridge",
        "IpcMode": "",
        "PidMode": "",
        "UTSMode": "",
        "CapAdd": null,
        "CapDrop": null,
        "RestartPolicy": {
            "Name": "always",
            "MaximumRetryCount": 0
        },
        "SecurityOpt": null,
        "ReadonlyRootfs": false,
        "Ulimits": null,
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "CgroupParent": ""
    },
    "Config": {
        "Hostname": "efd88d4e01c3",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": false,
        "AttachStderr": false,
        "PortSpecs": null,
        "ExposedPorts": null,
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "/bin/sh",
            "-c",
            "while true;do echo hello world;sleep 1;done"
        ],
        "Image": "centos:6.8",
        "Volumes": null,
        "VolumeDriver": "",
        "WorkingDir": "",
        "Entrypoint": null,
        "NetworkDisabled": false,
        "MacAddress": "",
        "OnBuild": null,
        "Labels": {
            "build-date": "2016-06-02",
            "license": "GPLv2",
            "name": "CentOS Base Image",
            "vendor": "CentOS"
        }
    }
}
]
[root@h1 ~]# 
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 轉載自 http://blog.opskumu.com/docker.html 一、Docker 簡介 Docke...
    極客圈閱讀 10,543評論 0 120
  • 一、Docker 簡介 Docker 兩個主要部件:Docker: 開源的容器虛擬化平臺Docker Hub: 用...
    R_X閱讀 4,409評論 0 27
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,953評論 6 342
  • 不可逾越的荒原 承載了多少不可訴說的心酸? 本應該坦然無波,適時成仙 只怪我執念太深,紅塵羈絆 也怪我太過懦弱,不...
    占戈蕭蕭閱讀 176評論 0 3
  • [心理話] 真的離開那個地方的時候,我也不知道我應該有什么樣的表情。 [懷念] 沒有打滴滴...
    盈盈淺笑7991閱讀 274評論 0 0