docker筑基篇-01-docker基础命令及常用选项

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。可以看出命令提示符也从root@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 ~]# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值