Docker 简明教程

Docker - Compose

Docker Compose 是一款专门设计用于简化多容器 Docker 应用程序管理的工具。它使用一个 YAML 文件,其中描述了应用程序所需的服務、网络和卷的定义。

Docker Compose is a tool specifically designed to simplify the management of multi-container Docker applications. It uses a YAML file in which the definition of services, networks, and volumes that an application requires is described.

基本上,通过 docker-compose.yml 文件,我们为每个容器定义配置:构建上下文、环境变量、要公开的端口以及服务之间的关系。可以通过一个命令( docker-compose up 命令)运行所有定义的服务,确保它们相应地协同工作。

Basically, through the docker-compose.yml file, we define the configuration for each container: build context, environment variables, ports to be exposed, and the relationship between services. Running all the defined services can be done by one command, the docker-compose up command, ensuring they work together accordingly.

Key Concepts of Docker Compose

Docker Compose 引入了几个基本概念,有必要理解并有效地使用该工具。这些概念包括以 YAML 编写的 Docker Compose 文件的架构、服务、网络、卷和环境变量。让我们讨论其中每一个概念。

Docker Compose introduces several essential concepts that are necessary to understand and be able to use the tool effectively. These consist of the architecture of a Docker Compose file written in YAML, services, networks, volumes, and environment variables. Let’s discuss each of these concepts.

Docker Compose File Mechanism (YAML)

通常,Docker Compose 文件将使用 YAML 的 docker-compose.yml 文件。该文件描述了应用程序可能需要的关于服务、网络和卷的配置。它提供了有关启动应用程序将运行于其下的环境的指南。理解此文件的结构对于有效使用 Docker Compose 至关重要。

Ordinarily, the Docker Compose file would be a docker-compose.yml file using YAML. The file describes the configuration your application might require regarding services, networks, and volumes. It gives a guide on spinning up the environment the application will run under. Understanding the structure of this file is crucial for effectively using Docker Compose.

  1. Version − This defines the format of the Docker Compose file so that it ensures compatibility with different Docker Compose features.

  2. Services − Contains lists of all services (containers) composing the application. Each service is described with uncounted configuration options.

  3. Networks − It will specify custom networks for inter-container communication and may specify the configuration options and network drivers.

  4. Volumes − Declares shared volumes that are used to allow persistent storage. Volumes can be shared between services or used to store data outside the container’s lifecycle.

version: '3.8'
services:
   web:
      image: nginx:latest
      ports:
         - "80:80"
      volumes:
         - web-data:/var/www/html
      networks:
         - webnet

   database:
      image: mysql:latest
      environment:
         MYSQL_ROOT_PASSWORD: example
      volumes:
         - db-data:/var/lib/mysql
      networks:
         - webnet

networks:
   webnet:
      driver: bridge

volumes:
   web-data:
   db-data:
docker compose file mechanism yaml

Docker Compose Services

Docker Compose 中的服务表示组成用户应用程序的容器。每个服务都在 services 部分中进行定义 docker-compose.yml 文件,并有其配置,如要使用的 Docker 映像、环境中的变量、端口、卷和网络设置。

Services in Docker Compose represent the containers comprising the user’s application. Each service is defined in the services section of the docker-compose.yml file and has its configuration such as a Docker image to use, variables within the environment, ports, volumes, and network settings.

  1. Image − This field specifies the Docker image that should be used for the service.

  2. Build − Specifies the directory for a build context, thus allowing the specification to make an image or not pull from a registry.

  3. Ports − maps host ports to the container.

  4. Volumes − Attach volumes to your service for persistent storage.

  5. Environment − Services environment variables.

  6. Depends_on − Defines service dependencies so they are started in the appropriate order.

services:
   app:
      image: myapp:latest
      build: .
      ports:
         - "8080:80"
      volumes:
         - app-data:/usr/src/app
      environment:
         - NODE_ENV=production
      depends_on:
         - db

   db:
      image: postgres:latest
      environment:
         POSTGRES_PASSWORD: example

Docker Compose Networks

Docker Compose 网络允许服务之间进行通信。默认情况下,Docker Compose 为 docker-compose.yml 下描述的所有服务定义了一个网络。但是,您可以定义自己的自定义网络,以更好地控制服务间通信。

Docker Compose networks allow for communication between services. By default, Docker Compose defines a single network for all services described under docker-compose.yml. However, you can define your custom networks to better control inter-service communication.

  1. driver − This specifies the driver to be used in the network (e.g., bridge, overlay).

  2. driver_opts − Options for the network driver.

  3. ipam − Specifies the IP address management configurations like subnets and IP ranges.

networks:
   frontend:
      driver: bridge
   backend:
      driver: bridge

services:
   web:
      networks:
         - frontend

   api:
      networks:
         - frontend
         - backend

   db:
      networks:
         - backend

Docker Compose Volumes

Docker Compose 使用卷,以保留由 Docker 容器创建或使用的的数据。 docker-compose.yml 文件中的 volumes 部分定义了附加到服务上的所有卷,以将数据存储在容器外部生命周期的方式中。

Docker Compose uses volumes to persist data created or consumed by Docker containers. The volumes section in the docker-compose.yml file defines all the volumes attached to services for storing data in a way that its lifecycle exists outside of the container.

  1. External − Indicates whether the volume is created outside Docker Compose.

  2. Driver − Specifies the volume driver to use.

  3. Driver_opts − Options to configure the volume driver.

volumes:
   db-data:
   app-data:
      external: true

services:
   database:
      image: postgres:latest
      volumes:
         - db-data:/var/lib/postgresql/data

   app:
      image: myapp:latest
      volumes:
         - app-data:/usr/src/app

Docker Compose Environment Variables

可以在 Docker Compose 中使用环境变量,以将配置设置传递到服务中。这些设置可以在服务的配置中定义为 environment 部分,或者从外部文件加载。

Environment variables can be used in Docker Compose to pass configuration settings into services. These can be defined within a service’s configuration as part of the environment section or loaded from an external file.

  1. Inline − Register environment variables within your service definition.

  2. env_file − This command allows environment variables to be loaded from an external file.

services:
   web:
      image: myapp:latest
      environment:
         - NODE_ENV=production
         - API_KEY=12345

   database:
      image: postgres:latest
      env_file:
         - .env

在 .env 文件中 −

In .env file −

POSTGRES_USER=myuser
POSTGRES_PASSWORD=mypassword
POSTGRES_DB=mydatabase

牢固掌握这些基本原理后,开发人员就可以使用 Docker Compose 管理和编排在 Docker 容器数量方面非常复杂且庞大的应用程序。

With a solid understanding of these basic principles, developers are well equipped to use Docker Compose in managing and orchestrating applications that are pretty complex and huge in terms of the number of Docker containers.

Important Docker Compose Commands

Docker Compose 是一个工具,用于使用有用的命令和操作(如启动、停止、构建、运行或对一个或多个容器执行其他操作)来管理 Docker 应用程序。本部分内容让我们了解必要的 Docker Compose 命令,并附有示例。

Docker Compose is a tool to manage Docker applications with useful commands and operations like start, stop, build, run, or execute another operation on one or several containers. In this section, let’s understand the necessary Docker Compose commands, that are accompanied by an example.

Docker Compose Up Command

docker-compose up 命令在 docker-compose.yml 文件中定义的全部应用程序中执行启动和运行,同时也创建并启动所有服务、网络和卷。此外,如果该服务的映像从未构建,它会构建必要的 Docker 映像。

The docker-compose up command brings up and runs the entire application, as defined in the docker-compose.yml file while creating and starting all the services, networks, and volumes. In addition, if images of this service have never been built, it builds the necessary Docker images.

$ docker-compose up
docker compose up command

Docker Compose Down Command

命令 docker-compose down 停止并移除在 docker-compose.yml 文件中定义的所有容器、网络和卷。因此,此命令有助于清理您的应用程序迄今为止所占用的资源,这意味着您可以确保没有残留容器或网络继续在某处运行。

The command docker-compose down stops and removes all the containers, networks, and volumes defined in the docker-compose.yml file. So, this command helps in cleaning up the resources that your app has taken so far, in the sense that you’re sure no residual container or network continues running somewhere.

$ docker-compose down
docker compose down command

Docker Build Command

该命令用于构建或重新构建 docker-compose.yml 文件中定义的服务的 Docker 映像。当 Dockerfile 或源代码发生更改时,就会运行该命令;需要创建新映像。

This command is used to build or rebuild Docker images for services defined in the docker-compose.yml file. It runs when changes are made in a Dockerfile or source code; new images need to be created.

$ docker-compose build

Docker Compose Start, Stop, Restart Commands

  1. docker-compose start will start the already created containers without recreating them, bringing up previously stopped services.

  2. docker-compose stop stops the currently running containers, without discarding them; thus, it is possible to restart the services later.

  3. docker-compose restart is useful if you’ve brought changes to the environment or configuration and want to restart them.

$ docker-compose start
$ docker-compose stop
$ docker-compose restart
docker compose start stop restart commands

Docker Compose Status Command

docker-compose ps 命令显示 docker-compose.yml 文件中定义的所有服务的当前运行状态,并指出了容器的状态、名称、状态和端口。此命令用于检查服务的当前运行状态。

The docker-compose ps command shows the status of all services defined in the docker-compose.yml file, pointing out containers' statuses, their names, states, and ports. This command is used to inspect the current state of the services.

$ docker-compose ps
docker compose status command

Docker Compose Logs Command

命令 docker-compose logs 可以获取并显示 docker-compose.yml 中定义所有服务的日志包。这对于调试和监控应用程序至关重要,因为这主要涉及从执行容器中获取实时输出。

The command docker-compose logs gets and displays the bundle of all logs that define services in docker-compose.yml. It is essential for debugging and monitoring the application because this will primarily involve real-time output from executing containers.

$ docker-compose logs
docker compose logs command

Docker Compose Exec Command

docker-compose exec 命令可以在正在运行的服务容器中运行任意命令。这可能会在应用程序中运行系统命令或在容器中直接执行脚本时派上用场。

The docker-compose exec command runs arbitrary commands in a running service container. This can be handy for running system commands inside your application or executing scripts directly within the container.

$ docker-compose exec <service_name> <command>
$ docker-compose exec web bash
docker compose exec command

Conclusion

总之,Docker Compose 是一款不可或缺的工具,可以管理多容器的 Docker 应用程序,既为基本设置提供简单性,也为更加复杂的场景提供强大功能。

In conclusion, Docker Compose is an indispensable tool for managing multi-container Docker applications, offering both simplicity for basic setups and powerful features for more complex scenarios.

无论您是本地开发、部署到生产环境还是集成到 CI/CD 管道,Docker Compose 都能提供管理集装箱化应用程序所需的灵活性以及控制功能。

Whether you are developing locally, deploying to production, or integrating with CI/CD pipelines, Docker Compose provides the flexibility and control needed to efficiently manage containerized applications.

FAQs on Docker Compose

1. How does Docker Compose handle dependencies between services?

在 yml 文件中使用 depends_on 属性时,Docker Compose 会自动解决服务之间的依赖性。如果一个服务依赖于另一个服务(例如,Web 服务器和数据库),Compose 会首先启动依赖服务,确保在启动依赖服务之前,依赖服务已启动并运行。这意味着无需手动干预,而且应用程序的启动也很顺利。

Docker Compose automatically resolves dependencies between services when the depends_on property is used in the yml file. If one depends on another (for example, a web server and a database), Compose starts the dependant first, ensuring that the dependencies are up and running before starting the dependent service. That means no manual intervention is needed, and your app’s startup is smooth.

2. Can I use Docker Compose in production environments?

虽然 Docker Compose 主要用于开发和测试,但是它在生产中也可用,但有一些需要注意的地方。Compose 确实简化了部署和扩展应用程序,但它缺乏大型生产环境所需的容量:负载均衡和滚动更新等内容。请考虑使用诸如 Docker Swarm 或 Kubernetes 等工具来编排和管理大型、高可用性的容器化应用程序,以便解决生产问题。

While Docker Compose is primarily designed for development and testing, it can be used in production with some caveats. Compose does make it simple to deploy and scale applications, but it lacks capabilities needed for very large-scale production environments: such things as load balancing and rolling updates. Consider using tools like Docker Swarm or Kubernetes for orchestrating and managing large-scale, highly available containerized applications in a production situation.