Docker容器使用

Docker 客户端

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

docker
Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/home/lei/.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 "/home/lei/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/home/lei/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/home/lei/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  app*        Docker App (Docker Inc., v0.9.1-beta3)
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.8.1-docker)
  compose*    Docker Compose (Docker Inc., v2.3.3)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.17.0)
  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.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/

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

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

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

容器相关命令

命令描述使用掌握程度
containerManage containers
createCreate a new container
runRun a command in a new container
attachAttach local standard input, output, and error streams to a running container
cpCopy files/folders between a container and the local filesystem
diffInspect changes to files or directories on a container’s filesystem
execRun a command in a running container
exportExport a container’s filesystem as a tar archive
portList port mappings or a specific mapping for the container
killKill one or more running containers
psList containers
renameRename a container
restartRestart one or more containers
rmRemove one or more containers
startStart one or more stopped containers
stopStop one or more running containers
topDisplay the running processes of a container

获取镜像

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

docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
Digest: sha256:626ffe58f6e7566e00254b638eb7e0f3b11d4da9675088f4781a50ae288f3322
Status: Image is up to date for ubuntu:latest
docker.io/library/ubuntu:latest

启动容器

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

docker run -it ubuntu /bin/bash

参数说明:

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

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

启动已停止运行的容器

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

docker ps -a

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

docker start a1abf166aa09

后台运行

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

docker run -itd --name ubuntu-test ubuntu /bin/bash
docker ps

**注:**加了 -d 参数默认不会进入容器,想要进入容器需要使用指令 docker exec(下面会介绍到)。

停止一个容器

停止容器的命令如下:

docker stop <容器 ID>

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

docker restart <容器 ID>

进入容器

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

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

attach 命令

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

docker ps
docker attach 8462af85f1b0 
#注意: 如果从这个容器退出,会导致容器的停止。
exit
docker ps

exec 命令

docker ps
docker exec -it 8462af85f1b0 /bin/bash

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

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

导出和导入容器

导出容器

docker export 8462af85f1b0 > ubuntu.tar

导入容器快照

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

cat ubuntu.tar |  docker import - test/ubuntu:v1
#输出:
sha256:2eb49c5272a8cba0ada9a15f2e6800f47b89e89fa07a08a2c9d9ab0785eb3bcb
#查看本地所有镜像
docker images

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

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

删除容器

删除容器使用 docker rm 命令:

docker ps -a
docker rm -f 8462af85f1b0
docker ps -a

下面的命令可以清理掉所有处于终止状态的容器。

docker container prune 

web应用例子

运行一个 web 应用

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

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

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

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

参数说明:

  • **-d:**让容器在后台运行。
  • **-P:**将容器内部使用的网络端口随机映射到我们使用的主机上。

查看 WEB 应用容器

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

docker ps
CONTAINER ID   IMAGE             COMMAND           CREATED         STATUS         PORTS                                         NAMES
81370b5ecde3   training/webapp   "python app.py"   9 seconds ago   Up 8 seconds   0.0.0.0:49153->5000/tcp, :::49153->5000/tcp   goofy_meitner

这里多了端口信息。

0.0.0.0:49153->5000/tcp, :::49153->5000/tcp

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

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

localhost:49153
#显示
Hello world!

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

docker run -d -p 5000:5000 training/webapp python app.py

docker ps查看正在运行的容器

CONTAINER ID   IMAGE             COMMAND           CREATED         STATUS         PORTS                                         NAMES
6a69e6937771   training/webapp   "python app.py"   4 seconds ago   Up 3 seconds   0.0.0.0:5000->5000/tcp, :::5000->5000/tcp     stoic_villani
81370b5ecde3   training/webapp   "python app.py"   7 minutes ago   Up 6 minutes   0.0.0.0:49153->5000/tcp, :::49153->5000/tcp   goofy_meitner

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

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

上面我们创建的 web 应用容器 ID 为 6a69e6937771 名字为 stoic_villani

我可以使用 docker port 6a69e6937771 或 docker port stoic_villani 来查看容器端口的映射情况。

docker port 6a69e6937771
docker port stoic_villani

查看 WEB 应用程序日志

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

docker logs -f stoic_villani
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
172.17.0.1 - - [28/Apr/2022 06:48:54] "GET / HTTP/1.1" 200 -
172.17.0.1 - - [28/Apr/2022 06:48:54] "GET /favicon.ico HTTP/1.1" 404 -

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

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

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

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

docker top stoic_villani

检查 WEB 应用程序

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

docker inspect stoic_villani

停止 WEB 应用容器

docker stop stoic_villani  

重启WEB应用容器

已经停止的容器,我们可以使用命令 docker start 来启动。

docker start stoic_villani
#查询最后一次创建的容器:
docker ps -l 

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

移除WEB应用容器

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

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

docker rm stoic_villani
  • 10
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值