Docker 简明教程
Docker - Containers
Docker 容器是 Docker 镜像的运行时实例。可以通过实例化镜像来创建它们。Docker 容器正在彻底改变软件开发、部署和管理。本质上,Docker 容器将应用程序与其所有依赖项捆绑到一个紧凑、轻量级的包中。它们可以通过在操作系统级别使用虚拟化在各种计算环境中可靠运行。
A Docker container is a runtime instance of a Docker image. They can be created by instantiating the image. Docker containers are completely changing software development, deployment, and management. In essence, Docker containers bundle an application along with all of its dependencies into a compact, light package. They can operate reliably in a range of computing environments by using virtualization at the operating system level.
此封装是通过使用 Docker images 来实现的。镜像本质上是蓝图,其中包含运行特定应用程序所需的所有文件、库和配置。由于容器将应用程序及其依赖项与底层系统隔离,因此它们在各种环境中提供一致性和可预测性。
This encapsulation is accomplished through the use of Docker images. Images are essentially blueprints that contain all the files, libraries, and configurations required to run a particular application. Since containers isolate the application and its dependencies from the underlying system, they offer consistency and predictability across a range of environments.
Docker 容器作为具有其文件系统、网络接口和资源的独立进程运行,但是它们很轻量级且高效,因为它们与主机操作系统共享相同的内核。它们依赖于 Docker 生态系统的关键组件才能工作,包括用于构建、启动和管理容器的 Docker 引擎和用作 Docker 镜像存储库的 Docker 注册表。
Docker Containers function as independent processes with their filesystem, network interface, and resources, but they are lightweight and efficient because they share the same kernel as the host operating system. They rely on key components of the Docker ecosystem to work, including the Docker Engine, which builds, launches, and manages containers, and the Docker Registry, which serves as a repository for Docker images.
在本章中,让我们了解容器的工作原理和最重要的 Docker 容器命令,你会最频繁地使用这些命令。
In this chapter, let’s understand how containers work and the important Docker container commands that you will you most frequently.
Key Concepts of Docker Containers
以下是 Docker 容器背后的关键概念和原则。
Here are the key concepts and principles that work behind Docker Containers.
Containerization
本质上,容器基于容器化概念运作,该概念将应用程序与其所有依赖项打包到单个包中。此包(称为容器镜像)包括运行应用程序所需的所有必要的运行时环境、库和其他组件。
Essentially, Containers function based on the concept of containerization, which is packing an application together with all of its dependencies into a single package. This package, referred to as a container image, includes all of the necessary runtime environments, libraries, and other components needed to run the application.
Isolation
Docker 容器使用操作系统级别的虚拟化来提供应用程序隔离。通过其文件系统、网络接口和进程空间,每个容器都作为独立进程独立于主机系统运行。
Operating system-level virtualization is used by Docker containers to offer application isolation. With its filesystem, network interface, and process space, each container operates independently of the host system as a separate process.
通过保持彼此之间的独立性,容器不会相互干涉操作,这要归功于这种隔离。
By maintaining their independence from one another, containers are kept from interfering with one another’s operations thanks to this isolation.
Docker Engine
Docker 引擎是 Docker 容器背后的核心;它构建、启动和维护它们。Docker 守护程序(在后台运行)和 Docker 客户端(允许用户通过命令与 Docker 守护程序通信)是构成 Docker 引擎的两个部分。
The Docker Engine is the brains behind Docker containers; it builds, launches, and maintains them. The Docker daemon, which operates in the background, and the Docker client, which lets users communicate with the Docker daemon via commands, are two of the parts that make up the Docker Engine.
Image and Container Lifecycle
创建容器镜像是 Docker 容器生命周期中的第一步。一个勾勒出应用程序的依赖性和配置的 Dockerfile 用于构建此镜像。
The creation of a container image is the first step in the lifecycle of a Docker container. A Dockerfile, which outlines the application’s dependencies and configuration, is used to build this image.
该镜像可用于实例化容器,这是一种在镜像创建后正在运行的镜像实例。可以将容器作为一个整体进行启动、停止、暂停和重启。
The image can be used to instantiate containers, which are instances of the image that are running after it has been created. It is possible to start, stop, pause, and restart containers as one.
Resource Management
Docker容器由于其共享内核架构和轻量设计,提供了有效的资源管理。由于容器共享主机系统的操作系统内核,因此开销减少,启动时间加快。
Docker containers provide effective resource management because of their shared kernel architecture and lightweight design. Since containers share the operating system kernel of the host system, overhead is decreased and startup times are accelerated.
为了确保最高性能和可扩展性,Docker还提供了用于资源使用情况监控和控制的工具。
To ensure maximum performance and scalability, Docker also offers tools for resource usage monitoring and control.
Portability
Docker容器的主要优点之一是其便携性。容器镜像是自包含的单元,可以轻松地在从生产到测试和开发的各种环境中部署和分发。
One of the main benefits of Docker containers is their portability. Container images are self-contained units that are easily deployable and distributed throughout various environments, ranging from production to testing and development.
这种可移植性通过启用“一处构建,随处运行”精简了部署过程,降低了出现兼容性问题的可能性。
This portability streamlines the deployment process and lowers the possibility of compatibility problems by enabling "build once, run anywhere".
Docker Container Lifecycle
Docker容器生命周期有五个基本阶段:创建、启动、暂停、退出和死亡。容器的生命周期由其阶段表示,该阶段从创建和执行到终止和可能的恢复。
There are five essential phases in the Docker container lifecycle: created, started, paused, exited, and dead. The lifecycle of a container is represented by its stages, which range from creation and execution to termination and possible recovery.
理解这些阶段对于熟练地监督Docker容器并确保其在容器化环境中的适当操作至关重要。
Comprehending these phases is crucial for proficiently overseeing Docker containers and guaranteeing their appropriate operation in a containerized setting.

让我们探讨Docker容器生命周期的阶段:
Let’s explore the stages of the Docker container lifecycle:
The Created State
“创建”状态是第一个阶段。当使用docker create命令或类似API调用创建容器时,它将进入此阶段。容器在“创建”状态下尚未运行,但它确实作为一个静态实体存在,其中定义了其所有配置设置。
The "created" state is the first stage. When a container is created with the docker create command or a comparable API call, it reaches this phase. The container is not yet running when it is in the "created" state, but it does exist as a static entity with all of its configuration settings defined.
此时,Docker保留容器所需的存储卷和网络接口,但容器内部的进程尚未开始。
At this point, Docker reserves the storage volumes and network interfaces that the container needs, but the processes inside the container have not yet begun.
The Started State
"已启动"或"正在运行"状态是生命周期的下一个阶段。当使用docker start命令或等效API调用启动容器时,它将进入此阶段。
The "started" or "running" state is the next stage of the lifecycle. When a container is started with the docker start command or an equivalent API call, it enters this stage.
当容器处于“启动”状态时,其进程被启动,并开始运行其镜像中指定的服务或应用程序。在此状态下,容器在执行其分配的任务时会主动使用CPU、内存和其他系统资源。
When a container is in the "started" state, its processes are launched and it starts running the service or application that is specified in its image. While they carry out their assigned tasks, containers in this state actively use CPU, memory, and other system resources.
The Paused State
在整个生命周期中,容器还可能进入“暂停”状态。当使用docker pause命令暂停容器时,它的进程将被挂起,从而停止其执行。
Throughout their lifecycle, containers may also go into a "paused" state. When a container is paused with the docker pause command, its processes are suspended, thereby stopping its execution.
已暂停的容器保留其资源分配和配置设置,但未处于使用状态。此状态有助于通过暂时停止容器执行(而不完全停止)来节省资源和进行调试。
A container that is paused keeps its resource allotments and configuration settings but is not in use. This state helps with resource conservation and debugging by momentarily stopping container execution without completely stopping it.
The Exited State
处于“退出”状态的容器已完成执行并已离开其主进程。容器在完成其预定完成的任务时或在遇到迫使其终止的错误时可以进入此状态。
A container in the "exited" state has finished executing and has left its primary process. Containers can enter this state when they finish the tasks they are intended to complete or when they run into errors that force them to terminate.
已“退出”的容器保持停止状态,保留其资源和配置设置,但不再运行任何进程。在此状态下,可以使用docker rm命令完全删除容器,或使用docker start命令重新启动容器。
A container that has been "exited" stays stopped, keeping its resources and configuration settings but ceasing to run any processes. In this condition, containers can be completely deleted with the docker rm command or restarted with the docker start command.
The Dead State
处于“死亡”状态的容器已遇到不可逆错误或被突然终止。容器化应用程序中的严重错误、底层主机系统的问题或手动干预都可能导致容器进入此状态。
A container that is in the "dead" state has either experienced an irreversible error or been abruptly terminated. Critical errors in the containerized application, problems with the host system underneath, or manual intervention can all cause containers to enter this state.
当容器处于“死亡”状态时,它不处于使用状态,Docker守护程序通常会释放或回收其资源。在此状态下的容器需要使用 docker rm command 删除,以释放系统资源,因为它们无法重新启动。
When a container is in the "dead" state, it is not in use and the Docker daemon usually releases or reclaims its resources. To free up system resources, containers in this state need to be deleted using the docker rm command since they cannot be restarted.
Important Docker Container Commands
现在您已了解Docker容器的基本知识及其工作原理,让我们借助示例来了解最重要的Docker容器命令。
Now that you have understood the basics of Docker Containers and how they work, let’s look at the most important Docker Container commands with the help of examples.
Listing all Docker Containers
使用 docker ps command 可列出 Docker 主机正在运行的容器。您可以使用 -a 或 --all 标记显示全部容器,包括已停止的容器,因为它默认为仅显示正在运行的容器。
The Docker host’s running containers can be listed using the docker ps command. You can use the -a or --all flag to show all containers, including stopped ones, as it only shows running containers by default.
$ docker ps

此命令显示当前正在运行的所有容器的 ID、名称、状态和其他相关详情。如果没有正在使用的容器,它会返回一个空列表。
This command displays the IDs, names, statuses, and other pertinent details of all containers that are currently running. It returns an empty list if no containers are in use.
Running a Docker Container
启动和创建 Docker 容器的主要命令为“docker run”。如果您本地尚未获得所需的映像,在运行此命令时,Docker 会从注册表中提取它。然后它会基于此映像生成一个新实例,从而启动一个全新的容器。
The primary command for starting and creating Docker containers is “docker run”. If the image isn’t already available locally, Docker pulls it from a registry when you run this command. It then starts a fresh container instance by generating one based on that image.
借助此命令,您可以指定多种选项,包括卷装载、环境变量、端口映射等,从而根据您的需求定制容器的配置。
With the help of this command, you can specify several options, including volume mounts, environment variables, port mappings, and more, to tailor the container’s configuration to your requirements.
$ docker run -d -p 8080:80 nginx

在此情况下,docker run 的分离模式 (-d) 会基于“nginx”映像创建一个新容器,并在后台运行它。此外,它将主机端口 8080 映射到容器端口 80 (-p 8080:80),从而授予对容器内 NGINX Web 服务器的访问权限。
In this case, the detached mode (-d) of the docker run creates a new container based on the "nginx" image and runs it in the background. Additionally, it maps host port 8080 to container port 80 (-p 8080:80), granting access to the NGINX web server housed within the container.
Stopping a Docker Container
可以使用 docker stop 命令从容地停止容器,该命令会向容器的主进程发送 SIGTERM。这会让容器完成任何清理操作,例如保存状态或在关闭之前切断网络连接。
A container can be gracefully stopped by using the docker stop command, which signals the container’s main process with a SIGTERM. This enables the container to finish any cleanup operations - such as saving state or cutting off network connections before shutting down.
$ docker stop my_container

此命令停止当前正在运行的“my_container”容器。Docker 会等待一段时间,直到容器从容地结束(默认时间为 10 秒)。如果容器未在此时间限制内停止,Docker 会自动使用 SIGKILL 信号终止它。
This command stops the "my_container" container that is currently operating. Docker waits for the container to gracefully end its life for a configurable duration (10 seconds by default). Docker will automatically terminate the container with a SIGKILL signal if it does not stop within this time limit.
Pausing a Running Container
正在运行的容器的进程可以通过 docker pause 命令暂时挂起,或暂停执行。这有助于临时释放系统资源、调试和解决问题。
A running container’s processes can be momentarily suspended, or its execution paused, with the docker pause command. This can be helpful for temporarily freeing up system resources, debugging, and troubleshooting problems.
$ docker pause my_container

此命令停止“my_container”容器运行。容器在暂停时不使用任何 CPU 或内存,因为它的进程已经被冻结。不过容器会保留它的资源分配和配置设置。
This command stops the container "my_container" from running. The container uses no CPU or memory when it is paused because its processes are frozen. The container does, however, keep its resource allocation and configuration settings.
Resuming a Docker Container
当容器暂停时,可以使用 docker unpause 命令恢复其进程。通过使用此命令,容器会返回到其初始状态,并撤销 docker pause 命令的影响。
When a container is paused, its processes can be carried out again by using the docker unpause command. By using this command, the container returns to its initial state and undoes the effects of the docker pause command.
$ docker unpause my_container

上述命令恢复已暂停容器“my_container”的执行,并允许其进程继续正常运行。
The above command resumes the paused container "my_container’s" execution and permits its processes to carry on as usual.
Restarting a Container
快速停止和重启正在运行的容器的一种简单方法是使用 docker restart 命令。它通常用于强制容器在出现问题后重新初始化,或者对正在运行的容器的配置应用更改。
One easy way to quickly stop and restart an operating container is with the docker restart command. It is frequently used to force a container to reinitialize after experiencing problems or to apply changes to the configuration of a running container.
$ docker restart my_container

此命令暂停“my_container.”容器,然后恢复其执行。容器内的进程在重启时停止,然后重启,从而使任何修改生效。
This command pauses and then resumes the execution of the container with the name "my_container.". The processes inside the container are stopped and then restarted upon restarting, enabling any modifications to take effect.
Executing Commands in a Running Docker Container
若要运行已经运行的容器中的某个命令,请使用 docker exec 命令。它允许用户在容器的环境中运行任意命令,例如启动一个 shell 会话或执行某个特定的程序。
To run a command inside an already-running container, use the docker exec command. It enables users to run arbitrary commands, like starting a shell session or carrying out a particular program, inside the environment of a container.
$ docker exec -it my_container bash

此命令会打开当前在交互式 shell 会话(bash)中运行的“my_container”容器。为了启用交互式输入/输出,-it 标记会分配一个伪 TTY,并在未连接时保持 STDIN 打开。
This command opens the "my_container" container that is currently running in an interactive shell session (bash). In order to enable interactive input/output, the -it flags allocate a pseudo-TTY and maintain STDIN open even when it is not attached.
Removing a Docker Container
若要移除一个或多个 Docker 容器,可以使用 docker rm 命令。可以指定您想要移除的容器的 ID 或名称。此命令默认仅删除已停止的容器;若要强制删除正在运行的容器,可以使用 -f 或 --force 标记。
To remove a Docker container or containers, you can use the docker rm command. The container(s) whose ID or name you wish to remove can be specified. This command only removes stopped containers by default; to forcefully remove running containers, you can use the -f or --force flag.
$ docker rm my_container

上述命令会删除名为“my_container.”的容器。除非使用 -f 标记来强制删除,否则容器必须在删除前停止运行。
The above command deletes the container with the name "my_container.". Unless the -f flag is used to force removal, the container must stop running before being removed.
若要清理 Docker 主机上的磁盘空间,可以使用 docker container prune 命令移除所有已停止的容器。这是一种清空空容器并回收资源的实用方法。
To clear up disk space on the Docker host, you can use the docker container prune command to remove all stopped containers. It is a practical method of clearing out empty containers and recovering resources.
$ docker container prune

Docker 要求您在继续之前进行确认,但您可以使用 -f 或 --force 标记来忽略此提示。
Docker asks for confirmation before continuing, but you can ignore this prompt by passing it with the -f or –force flag.
如果您想一起移除所有 Docker 容器,可以使用一个链式两条命令 - 用于获取所有容器 ID 列表的“docker ps -aq”,并将其与“docker rm”命令结合使用,以移除所有容器,包括正在运行的容器。
If you want to remove all Docker containers together, you can use a chain two commands - “docker ps -aq” which is used to obtain a list of all container IDs and combine it with the “docker rm” command to remove all containers, including running containers.
$ docker rm $(docker ps -aq)

以上命令将移除 Docker 主机上的各个容器,无论其是正在运行还是已停止。
The above command removes every container on the Docker host, regardless of whether it is running or stopped.
Conclusion
总之,Docker 容器完全改变了现代软件开发构建、部署和管理应用程序的方式。Docker 容器是轻量级和可移植的环境,可为打包和运行应用程序提供许多优势,例如一致性、可重复性、资源效率、可扩展性和可移植性。
To sum up, Docker containers have completely changed how modern software development builds, deploys, and manages applications. Docker containers are lightweight and portable environments that offer many advantages, such as consistency, repeatability, resource efficiency, scalability, and portability, for packaging and running applications.
通过使用一系列 Docker 命令和工具,开发人员可以轻松创建、部署和管理容器,从而促进更有效的开发工作流和增强的团队协作。随着容器化的发展势头,Docker 容器将保持作为软件开发生态系统关键组件的地位,帮助企业更快速地进行创新并更有效地为客户提供价值。
Using a range of Docker commands and tools, developers can easily create, deploy, and manage containers, facilitating more efficient development workflows and enhanced team collaboration. Docker containers are positioned to stay a key component of the software development ecosystem as containerization gains traction, helping businesses to innovate more quickly and provide value to clients more effectively.
FAQs
Q1. Is Docker a Container or a VM?
Docker 是一个容器化平台,这意味着它使用容器来运行和打包应用程序。与虚拟机 (VM) 将硬件虚拟化相反,Docker 容器共享主机的内核并对操作系统进行虚拟化。
Docker is a platform for containerization, meaning it uses containers to run and package apps. Docker containers share the host’s kernel and virtualize the operating system, in contrast to virtual machines (VMs), which virtualize hardware.
因此,由于 Docker 容器不需要为每个应用程序提供一个单独的操作系统实例,因此比虚拟机 (VM) 更轻量且更高效。
Because they do not need a separate operating system instance for each application, Docker containers are therefore more lightweight and efficient than virtual machines (VMs).
Q2. What is the difference between Docker and Kubernetes?
尽管它们有不同的用途,但 Docker 和 Kubernetes 都是容器生态系统中广泛使用的工具。Docker 提供了用于构建容器镜像并在本地或生产环境中运行容器的工具。它主要用于创建、管理和执行容器。
Although they have different uses, Docker and Kubernetes are both widely used tools in the container ecosystem. Docker offers tools for building container images and running containers locally or in production environments. It is mainly used for creating, managing, and executing containers.
借助 Kubernetes(一个用于容器编排的平台),可以将基于容器的应用程序的部署、扩展和管理自动化。Docker 专注于容器化过程本身,而 Kubernetes 管理容器群集并确保其具有弹性、可扩展性和可用性。
The deployment, scaling, and management of containerized apps can be automated with Kubernetes, a platform for container orchestration. Docker concentrates on the containerization process itself, whereas Kubernetes manages container clusters and makes sure they are resilient, scalable, and available.
Q3. How do I run a Docker Container?
您可以使用“ docker run <image> ”命令启动 Docker 容器。您必须提到一个 Docker 镜像的 ID 或名称,该镜像可在本地或通过注册表(例如 Docker Hub)获得。然后,使用 docker run 命令(后跟镜像的名称或 ID)从该镜像创建一个并启动一个容器。为了进一步自定义容器的配置,您可以选择提供更多参数,如端口映射、环境变量和卷装载。
You can use the "docker run <image>" command to start a Docker container. You have to mention the ID or name of a Docker image that is available either locally or through a registry such as Docker Hub. Then, to create and launch a container from that image, use the docker run command followed by the image’s name or ID. To further customize the container’s configuration, you can optionally provide more parameters like port mappings, environment variables, and volume mounts.
Q4. What is a Docker Daemon?
在主机系统上监督 Docker 容器的后台进程称为 Docker 守护进程或“ dockerd ”。它负责管理容器镜像、网络和卷,除了执行包括构建、启动、停止和移除容器在内的容器生命周期任务。Docker 守护进程与主机操作系统的内核交互以管理容器资源,同时侦听来自 Docker 客户端的 Docker API 请求并代表用户执行这些请求。
The background process that oversees Docker containers on a host system is called the Docker daemon, or "dockerd". It is in charge of managing container images, networks, and volumes in addition to performing container lifecycle tasks including building, launching, stopping, and removing containers. To manage container resources, the Docker daemon interacts with the host operating system’s kernel while listening for Docker API requests from the Docker client and executing them on the user’s behalf.
Q5. What is the Lifespan of a Docker Container?
Docker 容器的生存期可能根据其配置、创建方式以及它是在附加模式还是分离模式下操作而有所不同。Docker 容器通常会无限期地运行,除非其主进程结束或用户手动停止或终止它。
A Docker container’s lifetime may differ based on its configuration, how it was made, and whether it is operating in attached or detached mode. A Docker container typically runs indefinitely unless its main process ends or the user manually stops or terminates it.
当容器处于分离模式 (-d) 时,它们在后台运行,直到使用 docker stop 命令明确停止它们,或直到 Docker 守护进程重新启动。重启策略是另一种设置容器的方法,以便在发生故障或停止时它们将自行重启。
When containers are in detached mode (-d), they operate in the background until they are specifically stopped with the docker stop command or until the Docker daemon is restarted. Restart policies are another way to set up containers so that they will restart on their own in the event of a failure or stop.