Docker基础之六: Docker基础命令

简介: 容器相关的命令 在上例中,我们用3种方式运行了容器,在上节中我们学习了: docker ps : 查看容器列表 docker logs:查看容器的日志 docker stop:停止容器 在本节中,我们将通过事例来熟悉一些其他的docker命令,并学习docker client。 1 Doc

容器相关的命令

对Docker感兴趣的朋友可以加我的微信ghostcloud2016,然后我把你加到我们的一个Docker爱好者群组里面。

在上例中,我们用3种方式运行了容器,在上节中我们学习了:

  • docker ps : 查看容器列表
  • docker logs:查看容器的日志
  • docker stop:停止容器 在本节中,我们将通过事例来熟悉一些其他的docker命令,并学习docker client。

1 Docker Client

Docker Client和Docker Daemon实际使用的是同一个二进制程序,通过docker --help命令可以直接查看docker的所有命令及选项:

查看docker可执行程序的路径:

root@shev:~# which docker
/usr/bin/docker

docker命令的帮助信息:

root@shev:~# docker --help
Usage: docker [OPTIONS] COMMAND [arg...]
       docker daemon [ --help | ... ]
       docker [ --help | -v | --version ]

A self-sufficient runtime for containers.

Options:

  --config=~/.docker                 Location of client config files
  -D, --debug=false                  Enable debug mode
  --disable-legacy-registry=false    Do not contact legacy registries
  -H, --host=[]                      Daemon socket(s) to connect to
  -h, --help=false                   Print usage
  -l, --log-level=info               Set the logging level
  --tls=false                        Use TLS; implied by --tlsverify
  --tlscacert=~/.docker/ca.pem       Trust certs signed only by this CA
  --tlscert=~/.docker/cert.pem       Path to TLS certificate file
  --tlskey=~/.docker/key.pem         Path to TLS key file
  --tlsverify=false                  Use TLS and verify the remote
  -v, --version=false                Print version information and quit

Commands:
    attach    Attach 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 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 a container or image
    kill      Kill a running container
    load      Load an image from a tar archive or STDIN
    login     Register or log in to a Docker registry
    logout    Log out from a Docker registry
    logs      Fetch the logs of a container
    network   Manage Docker networks
    pause     Pause all processes within a container
    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 a container
    rm        Remove one or more containers
    rmi       Remove one or more images
    run       Run a command in a new container
    save      Save an image(s) to a tar archive
    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 a running container
    tag       Tag an image into a repository
    top       Display the running processes of a container
    unpause   Unpause all processes within a container
    version   Show the Docker version information
    volume    Manage Docker volumes
    wait      Block until a container stops, then print its exit code

Run 'docker COMMAND --help' for more information on a command.

具体的含义,我们在日后再一一讲解。我们先关注头几行:

Usage: docker [OPTIONS] COMMAND [arg...]
       docker daemon [ --help | ... ]
       docker [ --help | -v | --version ]

剖析:

  • 第一行实际是docker client的语法格式,它接收OPTIONS参数,并跟一个COMMAND,之后紧跟该命令对应的参数
  • 第二行实际是docker daemon的语法格式,有兴趣的朋友可以通过docker daemon –help进行查看
  • 第三行就是docker client的帮助,有需要都可以执行并查看。

一个我们经常用的查看docker版本信息的命令:

root@shev:~# docker version
Client:
 Version:      1.9.0
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   76d6bc9
 Built:        Tue Nov  3 17:43:42 UTC 2015
 OS/Arch:      linux/amd64

Server:
 Version:      1.9.0
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   76d6bc9
 Built:        Tue Nov  3 17:43:42 UTC 2015
 OS/Arch:      linux/amd64

这个命令会列出当前docker的client和server的基本信息.

2 通过容器来运行web应用

容器可以运行任何程序,那么一个主要的用途就是运行web应用,并对外提供服务,下面我们就用官方的一个例子来进行演示:

2.1 启动容器

root@shev:~# docker run -d -P training/webapp python app.py
Unable to find image 'training/webapp:latest' locally
latest: Pulling from training/webapp
2880a3395ede: Pull complete
515565c29c94: Pulling fs layer
98b15185dba7: Pulling fs layer
2ce633e3e9c9: Verifying Checksum
2ee0b8f351f7: Download complete
2505b734adda: Downloading [=====================>                             ] 8.732 MB/20.71 MB
20dd0c759013: Downloading [>                                                  ] 515.2 kB/50.25 MB
f95ebd363bf2: Verifying Checksum
1952e3bf3d7e: Download complete
abb991a4ed5e: Download complete
7cbae6914197: Pulling fs layer
f74dd040041e: Pulling fs layer
54bb4e8718e8: Download complete
Pulling repository docker.io/training/webapp
02a8815912ca: Download complete
e9e06b06e14c: Download complete
a82efea989f9: Download complete
37bea4ee0c81: Download complete
07f8e8c5e660: Download complete
23f0158a1fbe: Download complete
0a4852b23749: Download complete
7d0ff9745632: Download complete
99b0d955e85d: Download complete
33e109f2ff13: Download complete
cc06fd877d54: Download complete
b1ae241d644a: Download complete
b37deb56df95: Download complete
Status: Downloaded newer image for training/webapp:latest
docker.io/training/webapp: this image was pulled from a legacy registry.  Important: This registry version will not be supported in future versions of docker.
7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e

我们查看一下程序是否启动:

root@shev:~# docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                     NAMES
7736775bd89f        training/webapp                "python app.py"          9 minutes ago       Up 9 minutes        0.0.0.0:32768->5000/tcp   agitated_poitras
e221abf45a0b        ghostcloud.cn:5000/gcali:1.2   "/usr/local/ghostclou"   About an hour ago   Up About an hour                              gcsagent

剖析:

  • 我们从Docker Hub拉取了training用户下的webapp的最新版本,然后用python执行app.py
  • 我们的启动参数包括:-d 在后台运行,-P导出容器需要导出的端口,由于Docker Hub在国外,因此拉取的时间可能会有点长,但是一旦本地有了镜像,之后就会很快了。
  • 通过ps 命令,我们可以看到主机的32768端口映射到了容器的5000端口

2.2 访问网页

我们通过主机的32768端口进行访问: alt text

2.3 查看容器的端口导出情况

root@shev:~# docker port 7736
5000/tcp -> 0.0.0.0:32768

2.4 查看容器的运行日志

root@shev:~# docker logs -f 7736
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
192.168.0.103 - - [02/Dec/2015 10:03:07] "GET / HTTP/1.1" 200 -
192.168.0.103 - - [02/Dec/2015 10:03:07] "GET /favicon.ico HTTP/1.1" 404 -
192.168.0.103 - - [02/Dec/2015 10:08:11] "GET / HTTP/1.1" 200 -

剖析:

  • -f会一直绑定到容器的标准输出上,不带-f时,运行后命令立刻就会退出
  • 运行完logs –f后,我们访问网页时,就会在命令行里面显示日志

2.5 查看容器中的进程信息

root@shev:~# docker top 7736
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                5115                4051                0                   17:53               ?                   00:00:00            python app.py

2.6 查看容器的详细信息

root@shev:~# docker inspect 7736
[
{
    "Id": "7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e",
    "Created": "2015-12-02T09:53:41.35592583Z",
    "Path": "python",
    "Args": [
        "app.py"
    ],
    "State": {
        "Status": "running",
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 5115,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2015-12-02T09:53:41.62798274Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "02a8815912ca800f99b7d912485e8c618260e27c6de8d7a161b356b322d5c121",
    "ResolvConfPath": "/var/lib/docker/containers/7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e/hostname",
    "HostsPath": "/var/lib/docker/containers/7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e/hosts",
    "LogPath": "/var/lib/docker/containers/7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e/7736775bd89f6d0373b7a6c39a91126d156d9b0ce5467c30f0275506e012be4e-json.log",
    "Name": "/agitated_poitras",
    "RestartCount": 0,
    "Driver": "aufs",
    "ExecDriver": "native-0.2",
    "MountLabel": "",
    "ProcessLabel": "",
    "AppArmorProfile": "",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LxcConf": [],
        "Memory": 0,
        "MemoryReservation": 0,
        "MemorySwap": 0,
        "KernelMemory": 0,
        "CpuShares": 0,
        "CpuPeriod": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "CpuQuota": 0,
        "BlkioWeight": 0,
        "OomKillDisable": false,
        "MemorySwappiness": -1,
        "Privileged": false,
        "PortBindings": {},
        "Links": null,
        "PublishAllPorts": true,
        "Dns": null,
        "DnsOptions": null,
        "DnsSearch": null,
        "ExtraHosts": null,
        "VolumesFrom": null,
        "Devices": [],
        "NetworkMode": "default",
        "IpcMode": "",
        "PidMode": "",
        "UTSMode": "",
        "CapAdd": null,
        "CapDrop": null,
        "GroupAdd": null,
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "SecurityOpt": null,
        "ReadonlyRootfs": false,
        "Ulimits": null,
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "CgroupParent": "",
        "ConsoleSize": [
            0,
            0
        ],
        "VolumeDriver": ""
    },
    "GraphDriver": {
        "Name": "aufs",
        "Data": null
    },
    "Mounts": [],
    "Config": {
        "Hostname": "7736775bd89f",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": false,
        "AttachStderr": false,
        "ExposedPorts": {
            "5000/tcp": {}
        },
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "python",
            "app.py"
        ],
        "Image": "training/webapp",
        "Volumes": null,
        "WorkingDir": "/opt/webapp",
        "Entrypoint": null,
        "OnBuild": null,
        "Labels": {},
        "StopSignal": "SIGTERM"
    },
    "NetworkSettings": {
        "Bridge": "",
        "SandboxID": "02c2de9e7171ed418869e53297b0b1956052be67d2c9c4c75f99829fff646fdd",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {
            "5000/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "32768"
                }
            ]
        },
        "SandboxKey": "/var/run/docker/netns/02c2de9e7171",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "f623f99d87ec63cc3bfdc024886d24d40bd1cf1771e249951133a7c66424d6e9",
        "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": {
                "EndpointID": "f623f99d87ec63cc3bfdc024886d24d40bd1cf1771e249951133a7c66424d6e9",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02"
            }
        }
    }
}
]

2.7 停止并重启容器

root@shev:~# docker stop 7736

7736
root@shev:~#
root@shev:~# docker start 7736
7736
root@shev:~# docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                     NAMES
7736775bd89f        training/webapp                "python app.py"          25 minutes ago      Up 2 seconds        0.0.0.0:32769->5000/tcp   agitated_poitras

注意:容器的在主机上的映射端口变成了32769,原因是我们没有指定主机的端口。

2.8 指定主机和容器的端口映射

root@shev:~# docker run -d -p 80:5000 training/webapp python app.py
54132a474d29d44a7fc6431184ae1c1c77b4c8fb31975d477aab73647a008837

root@shev:~# docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                     NAMES
54132a474d29        training/webapp                "python app.py"          3 seconds ago       Up 2 seconds        0.0.0.0:80->5000/tcp      grave_williams

剖析:

  • 通过-p 参数可以指定端口映射,通过-P则是随机分配
  • 由于我们导出主机的80端口,因此我们再次访问网页的时候,可以不需要指定端口: alt text

是不是眼前一亮,是的,我们可以将我们的网页直接运行在容器里面! 想象一下,你拥有一台云主机……

目录
相关文章
|
18天前
|
安全 Docker 容器
|
18天前
|
网络安全 数据安全/隐私保护 Docker
|
5天前
|
Java 应用服务中间件 Linux
【Docker容器化技术】docker安装与部署、常用命令、容器数据卷、应用部署实战、Dockerfile、服务编排docker-compose、私有仓库
本文主要讲解了Docker的安装与部署、常用命令、容器数据卷、应用部署实战、Dockerfile、服务编排docker-compose、私有仓库以及Docker容器虚拟化与传统虚拟机比较。
【Docker容器化技术】docker安装与部署、常用命令、容器数据卷、应用部署实战、Dockerfile、服务编排docker-compose、私有仓库
|
16天前
|
存储 监控 安全
|
2月前
|
Linux Docker 容器
Docker操作 :容器命令
Docker操作 (四)
|
17天前
|
存储 关系型数据库 MySQL
|
25天前
|
网络协议 Docker 容器
docker pull命令拉取镜像失败的解决方案
docker pull命令拉取镜像失败的解决方案
567 1
|
26天前
|
安全 网络安全 开发者
Docker学习笔记(一):Docker命令总结
本文介绍了Docker的基本概念、优点以及常用命令。Docker是一个开源的应用容器引擎,它通过容器打包应用程序及其依赖项,实现快速部署和迁移。主要优点包括轻量级、可移植性、易于管理、安全性和开源性。文章还区分了镜像和容器的概念,并提供了构建镜像、查看容器、运行容器、停止和删除容器等常用Docker命令的示例。
124 0
|
1月前
|
Linux 网络安全 Docker
安装后无法使用 Docker 命令
【10月更文挑战第3天】
138 2
|
1月前
|
安全 Shell Linux
docker进入容器命令
docker进入容器命令
下一篇
无影云桌面