Docker 简明教程

Docker - Working with Containers

Docker 容器是一个可移植的软件单元,它打包一个应用程序及其所有依赖项,以便在任何基础设施上运行。所以,该应用程序在很多开发、测试和生产环境中始终如一地运行。本章重点介绍 Docker 容器的一些基本命令,这将帮助您无缝地使用容器。

A Docker Container is a portable software unit that packages up an application and all its dependencies to run on any infrastructure. The application, hence runs consistently in many development, testing, and production environments. This chapter focuses on some basic commands for Docker containers which will help you to seamlessly work with containers.

Important Docker Container Commands

Docker 附带了很多命令,这些命令可用于构建、管理和运行容器。这些命令对于使用 Docker 至关重要;它们使您可以非常有效地控制容器的生命周期和行为。了解和精通使用这些命令对于有效利用 Docker 至关重要。

Docker ships with many commands that can be used to build, manage, and run containers. These commands are fundamental in working with Docker; they empower you to control both the life cycle and behavior of containers in a very efficient way. Knowing and mastering the use of these commands is crucial to leverage Docker effectively.

Creating and Starting Containers - docker run command

docker run 命令创建一个新容器并启动它。它包括从存储库中提取映像(如果它不在您的本地系统上)、创建容器并启动一个容器的功能。可以传递多个选项和标记来改变容器的行为,例如设置环境变量、挂载卷和配置网络。

The docker run command creates a new container and starts it. It includes the functionalities of pulling an image from a repository (if it’s not already on your local system), creating a container, and starting one. Several options and flags can be passed to alter the container’s behavior, like setting environment variables, mounting volumes, and configuring networking.

$ docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
$ docker run -d -p 80:80 --name mywebserver nginx
creating and starting containers

此命令将在分离模式 (-d) 下启动我们的 nginx web 服务器容器,将宿主的 80 端口暴露给容器的 80 端口 (-p 80:80),并将容器命名为 my webserver。

This command will launch our nginx web server container in detached mode (-d), expose port 80 of the host to port 80 of the container (-p 80:80), and name the container my webserver.

Listing Containers

docker ps 命令用于列出所有正在运行的容器。默认情况下,它只列出正在运行的容器,但人们可以提供额外的标记来包括已停止的容器或根据任意标准过滤结果。此命令输出重要信息,如容器 ID、名称、状态和启动特定容器的命令。

The docker ps command is used to list all running containers. By default, it only lists the running containers, but one can provide extra flags to include stopped containers or filter the results based on arbitrary criteria. This command outputs vital information such as container IDs, names, statuses, and the command that started a particular container.

$ docker ps
$ docker ps -a
listing containers

此命令列出所有容器,包括已停止的容器 (-a)。

This command lists all containers, including those that are stopped (-a).

Managing Container States

以下是要用于控制容器状态的命令。

These are the commands used to control the states of containers.

  1. Docker Start − Start one or more stopped containers.

  2. Docker Stop − Stop running containers gracefully to have time for their correct shutdown.

  3. Docker Restart − Stops and then starts one or more containers, effectively rebooting them.

$ docker start [CONTAINER]
$ docker stop [CONTAINER]
$ docker restart [CONTAINER]
$ docker start mywebserver
$ docker stop mywebserver
$ docker restart mywebserver
managing container states

上述命令分别启动、停止和重新启动一个名为 my webserver 的容器。

The above commands, respectively start, stop, and restart a container named my webserver.

Viewing Container Logs

人们可以使用 docker logs 命令来从正在运行或已停止的容器中提取日志。它将提供对容器的输出及其行为的视图,这对于调试和监视目的非常有帮助。您还可以关注实时日志或将输出限制为最近的日志条目。

One can use the docker logs command to extract the logs from a running or stopped container. It will provide a view of the container’s output and its behavior, which can be very helpful for debugging and monitoring purposes. You can also follow real-time logs or limit the output to recent log entries.

$ docker logs [OPTIONS] CONTAINER
$ docker logs mywebserver
viewing container logs

这个命令显示 mywebserver 容器的日志。

This command displays the logs of the mywebserver container.

Removing Containers

docker rm 命令删除一个或多个容器。它对于清除不再需要的容器很有用。要删除正在运行的容器,你必须先停止它或使用 -f (强制) 选项强制删除它。

The docker rm command removes one or more containers. It is useful for cleaning up containers that are no longer needed. To remove a running container, you must stop it first or use the -f (force) option to forcibly remove it.

$ docker rm [OPTIONS] CONTAINER [CONTAINER...]
$ docker rm mywebserver
removing containers

这个命令删除 mywebserver 容器。

This command removes the mywebserver container.

Creating Images from Containers

docker commit 命令根据容器中的更改提交一个新镜像。当你想要在当前时刻保存容器的状态,然后与他人共享该状态或在另一个容器中再次使用它时,它很有用。

The docker commit command commits a new image based on changes from a container. It’s useful when you want to save the state of a container at the current moment in time and then share that state with someone or use it again in another container.

$ docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
$ docker commit mywebserver mynewimage
creating images from containers

这个命令将使用 webserver 容器创建一个新镜像,名为 mynewimage。

This command will create a new image from the webserver container, mynewimage.

Other Key Commands

Docker 还有几个其他命令来操作和管理容器。

Docker also has several other commands to work with and manage containers.

  1. Docker exec − Execute a command in an active container.

  2. Docker cp − Copy files/folders between a container and the local filesystem.

  3. Docker top − Display the running processes of a container.

  4. Docker attach − Attach to a running container to interact with it.

  5. Docker pause and unpause − These are for pausing the container process and resuming it, respectively.

下面的命令在 mywebserver 容器中交互式地运行 Bash shell。

The below command runs a Bash shell in the mywebserver container interactively.

$ docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
$ docker exec -it mywebserver /bin/bash

下一个命令将 /var/www/html 的内容从 mywebserver 容器复制到本地 ./local_copy 目录。

The next command copies the contents of /var/www/html from the mywebserver container to the local ./local_copy directory.

$ docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
$ docker cp mywebserver:/var/www/html ./local_copy

下面的命令显示 mywebserver 容器的正在运行的进程。

The below command displays the running processes of the mywebserver container.

$ docker top CONTAINER [ps OPTIONS]
$ docker top mywebserver
other key commands 1

下一个命令将你的终端连接到 mywebserver 容器。

The next command attaches your terminal to the mywebserver container.

$ docker attach [OPTIONS] CONTAINER
$ docker attach mywebserver
other key commands 2

后续命令分别暂停和取消暂停 mywebserver 容器。

The subsequent commands pause and unpause the mywebserver container, respectively.

$ docker pause CONTAINER [CONTAINER...]
$ docker unpause CONTAINER [CONTAINER...]
$ docker pause mywebserver
$ docker unpause mywebserver
other key commands 3

Publishing Container Ports

发布容器端口使容器服务从 Docker 主机之外可以访问。通过将容器端口映射到主机端口,你可以将容器内部运行的服务暴露给外部客户端。

Publishing of container ports makes container services accessible from outside the Docker host. By mapping container ports to host ports, you can expose the services running inside the container to external clients.

$ docker run -p HOST_PORT:CONTAINER_PORT [OPTIONS] IMAGE [COMMAND] [ARG...]
$ docker run -d -p 8080:80 --name webserver nginx
publishing container ports

上面的命令将运行一个 nginx 容器并将容器的 80 端口映射到主机上的 8080 端口,从而允许在 [role="bare"] [role="bare"]http://localhost:8080 访问 Web 服务器。

The above command will run an nginx container and map the port 80 of the container to the port 8080 on the host, allowing the webserver to be accessed at [role="bare"]http://localhost:8080.

Resource Management (CPU, Memory, IO)

Docker 提供了几种功能来设置限制和管理分配给容器的资源。这可以防止单个容器不公平地使用资源。

Docker offers several capabilities for setting limits and managing the resources allocated to a container. This safeguards against single-container resource utilization in an unfair manner.

CPU Limits

$ docker run --cpus="1.5" [OPTIONS] IMAGE [COMMAND] [ARG...]

此命令限制容器最多使用 1.5 个 CPU 内核。

This command restricts the container to use a maximum of 1.5 CPU cores.

Memory Limits

$ docker run --memory="512m" [OPTIONS] IMAGE [COMMAND] [ARG...]

此命令限制容器最多使用 512 MB 内存。

This command limits the container to a maximum of 512 MB of memory.

IO Limits

$ docker run --blkio-weight=500 [OPTIONS] IMAGE [COMMAND] [ARG...]

此命令初始化容器的块 IO 权重;用户可以影响 IO 优先级。

This command initializes the block IO weight for the container; the user can influence the IO priority.

Conclusion

借助功能强大的容器化平台的支持,Docker 重新定义了软件开发和部署格局。在使用 Docker 发挥其全部潜能时,理解和掌握其基本命令、网络功能、高级操作和最佳实践至关重要。

Docker has redefined the landscape of software development and deployment with the support of a powerful containerization platform. It’s important to understand and master its essential commands, networking capabilities, advanced operations, and best practices when using Docker to harness its full potential.

随着您继续研究和花费时间使用 Docker,这些基本和高级概念将帮助您构建、管理和部署不仅可扩展、安全,而且高效的应用程序。

As you continue to tinker with and spend time using Docker, these basic and advanced concepts will help enable you to build, manage, and deploy not only scalable, and secure, but also efficient applications.

FAQs on Docker Working with Containers

1. How does Docker isolate containers from each other and the host system?

命名空间和控制组主要在 Docker 中实现隔离。命名空间提供隔离 - 它们允许每个容器使用具有独立进程列表、网络设置和文件系统的系统视图。

Namespaces and control groups mainly implement isolation in Docker. Namespaces provide isolation - they allow each container its view of the system with an independent process list, network setup, and file system.

控制组一次限制容器可以使用资源的量,以确保在 CPU、内存或 I/O 方面的重负载情况下,它不会饿死系统中的其他部分。这种隔离确保了包含的应用程序可以独立运行,而不会干扰其他应用程序或基础主机。

Control groups limit the amount of resources a container can use at once to ensure that it cannot starve the rest of the system in cases of heavy loads in terms of CPU, memory, or I/O. Such isolation ensures that the contained application can run independently without interfering with other applications or the underlying host.

2. Can I use Docker on a production server?

是的,重要的是要强调 Docker 在生产环境中被大量使用。组织在容器中运行服务,以可靠地打包和将应用程序部署到不同平台。

Yes, it’s important to emphasize that Docker is heavily used in production environments. Organizations run services in containers to package and deploy applications onto different platforms reliably.

在投入生产时,请务必遵循安全性、监视和可扩展性的最佳实践。您可以使用编排工具(如 Docker Swarm 或 Kubernetes)来帮助管理大规模的 Docker 部署。

Be sure to follow best practices for security, monitoring, and scalability as you come into production. You can use orchestration tools like Docker Swarm or Kubernetes to help manage large-scale Docker deployments.

3. How do I update a Docker container without losing its data?

要无损地更新容器,您首先停止容器。您从注册表中拉取更新的映像,在从注册表中拉取更新的映像后,您删除旧的现有容器 - 使用 "-v" flag on docker rm 保留其卷。

To update a container non-destructively, you first stop the container. You pull an updated image from the registry, and after pulling an updated image from the registry, you remove the old existing container - preserving its volumes with the "-v" flag on docker rm.

最后,使用更新的映像启动新容器,并挂载同一卷到前一个映像。通过这种方式,您的数据在更新后仍将保持一致。

Finally, use the updated image to start a new container and mount the same volumes in the previous one. This way, your data will still be consistent after the update.