Docker 容器使用

Reads: 620 Edit

Docker 客户端

docker 客户端非常简单 ,我们可以直接输入 docker 命令来查看到 Docker 客户端的所有命令选项。

[root@localhost ~]# docker

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.

可以通过命令 docker command --help 更深入的了解指定的 Docker 命令使用方法。

例如我们要查看 docker stats 指令的具体使用方法:

[root@localhost ~]#  docker stats --help

Usage:  docker stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

容器使用

获取镜像 如果我们本地没有 ubuntu 镜像,我们可以使用 docker pull 命令来载入 ubuntu 镜像:

[root@localhost ~]# docker pull ubuntu

启动容器

以下命令使用 ubuntu 镜像启动一个容器,参数为以命令行模式进入该容器:

[root@localhost ~]#  docker run -it ubuntu /bin/bash

aaa3313

参数说明:

  • -i: 交互式操作。

  • -t: 终端。

  • ubuntu: ubuntu 镜像。

  • /bin/bash:放在镜像名后的是命令,这里我们希望有个交互式 Shell,因此用的是 /bin/bash。

要退出终端,直接输入 exit:

root@f416ae82ef04:/# exit
exit
[root@localhost ~]# 

启动已停止运行的容器

查看所有的容器命令如下:

[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
3e1c55f9cc84        ubuntu              "/bin/bash"         22 seconds ago      Exited (0) 19 seconds ago                       great_colden

使用 docker start 启动一个已停止的容器:

[root@localhost ~]# docker start 3e1c55f9cc84
3e1c55f9cc84

后台运行 在大部分的场景下,我们希望 docker 的服务是在后台运行的,我们可以过 -d 指定容器的运行模式。

[root@localhost ~]# docker run -itd --name ubuntu-test ubuntu /bin/bash
eacc205442d9f35e95c9620d50f7bef4a0b5c6dad105a16743521658afb912d9
[root@localhost ~]# 

加了 -d 参数默认不会进入容器,想要进入容器需要使用指令 docker exec

停止一个容器 停止容器的命令如下:

$ docker stop <容器 ID>

实例

[root@localhost ~]# docker stop 3e1c55f9cc84
3e1c55f9cc84

停止的容器可以通过 docker restart 重启:

$ docker restart <容器 ID>

实例

[root@localhost ~]# docker restart 3e1c55f9cc84
3e1c55f9cc84

进入容器 在使用 -d 参数时,容器启动后会进入后台。此时想要进入容器,可以通过以下指令进入:

  • docker attach

  • docker exec:推荐大家使用 docker exec 命令,因为此退出容器终端,不会导致容器的停止。

attach 命令

下面演示了使用 docker attach 命令。

[root@localhost ~]# docker attach 3e1c55f9cc84
root@3e1c55f9cc84:/# 

注意: 如果从这个容器退出,会导致容器的停止。 exec 命令

下面演示了使用 docker exec 命令。

[root@localhost ~]# docker exec -it 3e1c55f9cc84 /bin/bash
root@3e1c55f9cc84:/# 

注意: 如果从这个容器退出,不会导致容器的停止,这就是为什么推荐大家使用 docker exec 的原因。

更多参数说明请使用 docker exec --help 命令查看。

导出和导入容器

导出容器

如果要导出本地某个容器,可以使用 docker export 命令。

[root@localhost ~]# docker export eacc205442d9  > ubuntu.tar

这样将导出容器快照到本地文件。

导入容器快照

可以使用 docker import 从容器快照文件中再导入为镜像,以下实例将快照文件 ubuntu.tar 导入到镜像 test/ubuntu:v1:

[root@localhost ~]#  cat ubuntu.tar | docker import - test/ubuntu:v1
sha256:c36c435a0a0391ca65b9cb29cf7c4bc0861d15632381851735bb1c47ad06cce9

此外,也可以通过指定 URL 或者某个目录来导入,例如:

$ docker import http://example.com/exampleimage.tgz example/imagerepo

删除容器

删除容器使用 docker rm 命令:

[root@localhost ~]# docker rm -f eacc205442d9
eacc205442d9
[root@localhost ~]# 

运行一个 web 应用

前面我们运行的容器并没有一些什么特别的用处。

接下来让我们尝试使用 docker 构建一个 web 应用程序。

我们将在docker容器中运行一个 Python Flask 应用来运行一个web应用。

$ docker pull training/webapp  # 载入镜像
$ docker run -d -P training/webapp python app.py

实例

[root@localhost ~]# docker run -d -P training/webapp python app.py
2930266d307d91bb543a80bfb9d6a0d7b0ecae354a6860c13502b33ccbdac3d6

参数说明:

  • -d:让容器在后台运行。

  • -P:将容器内部使用的网络端口映射到我们使用的主机上。

查看 WEB 应用容器

使用 docker ps 来查看我们正在运行的容器:

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                     NAMES
2930266d307d        training/webapp     "python app.py"     56 seconds ago      Up 55 seconds       0.0.0.0:32768->5000/tcp   wizardly_davinci
3e1c55f9cc84        ubuntu              "/bin/bash"         2 hours ago         Up 27 minutes                                 great_colden

这里多了端口信息。

0.0.0.0:32768->5000/tcp

Docker 开放了 5000 端口(默认 Python Flask 端口)映射到主机端口 32769 上。

这时我们可以通过浏览器访问WEB应用

QQ截图20191223005952

我们也可以通过 -p 参数来设置不一样的端口:

[root@localhost ~]# docker run -d -p 5000:5000 training/webapp python app.py
fb83c73dbeb993ef9e61309809c98067f95402e52e1a28af3cb27b179f448c81

docker ps查看正在运行的容器

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                     NAMES
fb83c73dbeb9        training/webapp     "python app.py"     22 seconds ago      Up 21 seconds       0.0.0.0:5000->5000/tcp    gallant_curran
2930266d307d        training/webapp     "python app.py"     3 minutes ago       Up 3 minutes        0.0.0.0:32768->5000/tcp   wizardly_davinci
3e1c55f9cc84        ubuntu              "/bin/bash"         2 hours ago         Up 30 minutes                                 great_colden

容器内部的 5000 端口映射到我们本地主机的 5000 端口上。

网络端口的快捷方式

通过 docker ps 命令可以查看到容器的端口映射,docker 还提供了另一个快捷方式 docker port,使用 docker port 可以查看指定 (ID 或者名字)容器的某个确定端口映射到宿主机的端口号。

上面我们创建的 web 应用容器 ID 为 bf08b7f2cd89 名字为 wizardly_chandrasekhar。

我可以使用 docker port fb83c73dbeb9docker port wizardly_davinci 来查看容器端口的映射情况。

[root@localhost ~]# docker port fb83c73dbeb9
5000/tcp -> 0.0.0.0:5000
[root@localhost ~]# docker port wizardly_davinci
5000/tcp -> 0.0.0.0:32768

查看 WEB 应用程序日志

docker logs [ID或者名字] 可以查看容器内部的标准输出。

[root@localhost ~]# docker logs -f fb83c73dbeb9
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

-f: 让 docker logs 像使用 tail -f 一样来输出容器内部的标准输出。

从上面,我们可以看到应用程序使用的是 5000 端口并且能够查看到应用程序的访问日志。

查看WEB应用程序容器的进程

我们还可以使用 docker top 来查看容器内部运行的进程

[root@localhost ~]# docker top 2930266d307d
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                10058               10041               0                   00:57               ?                   00:00:00            python app.py

检查 WEB 应用程序

使用 docker inspect 来查看 Docker 的底层信息。它会返回一个 JSON 文件记录着 Docker 容器的配置和状态信息。

[root@localhost ~]# docker inspect  2930266d307d

停止 WEB 应用容器

[root@localhost ~]# docker stop 2930266d307d

重启WEB应用容器

[root@localhost ~]# docker start 2930266d307d
2930266d307d

docker ps -l查询最后一次创建的容器: 实例

[root@localhost ~]# docker ps -l 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
fb83c73dbeb9        training/webapp     "python app.py"     7 minutes ago       Up 7 minutes        0.0.0.0:5000->5000/tcp   gallant_curran
[root@localhost ~]# 

正在运行的容器,我们可以使用 docker restart 命令来重启。

移除WEB应用容器

我们可以使用 docker rm 命令来删除不需要的容器

[root@localhost ~]# docker rm  2930266d307d
2930266d307d
[root@localhost ~]# 

删除容器时,容器必须是停止状态,否则会报如下错误

[root@localhost ~]# docker rm  2930266d307d
Error response from daemon: You cannot remove a running container 2930266d307d91bb543a80bfb9d6a0d7b0ecae354a6860c13502b33ccbdac3d6. Stop the container before attempting removal or force remove

关于作者

王硕,十年软件开发经验,业余产品经理,精通Java/Python/Go等,喜欢研究技术,著有《PyQt快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流:


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。