docker compose 中服务和容器的区别

Difference between service and container in docker compose

我正在 docker 撰写中查看 volumes_from 选项。显然,您可以从容器或服务中导入卷。从 docker 撰写文档是:

volumes_from

Mount all of the volumes from another service or container, optionally specifying read-only access(ro) or read-write(rw).

volumes_from:
 - service_name
 - service_name:ro
 - container:container_name
 - container:container_name:rw

Note: The container:... formats are only supported in the version 2 file format. In version 1, you can use container names without marking them as such:

- service_name
- service_name:ro
- container_name
- container_name:rw

我在这里很困惑容器和服务之间的区别是什么?

我不能完全回答你的问题,因为我自己不了解服务。 但是,我确实理解 volumes_from 与容器的关系,所以这将回答你一半的问题 :) 部分答案优于 none?

容器 A

volumes: /my/shared/directory
container_name:ca

容器 B

volumes_from:ca

现在容器 B 将有一个新目录 /my/shared/directory 从容器 A 挂载 - 容器 B 中目录的内容将与容器 A 中目录的内容完全相同

如果您发现有关服务,请告诉我

服务和容器是相关的,但两者是不同的东西。

一项服务可以由一个或多个容器运行。 使用 docker 可以处理容器,使用 docker-compose 可以处理服务。

例如:

假设我们有这个 docker-compose.yml 文件:

web:
  image: example/my_web_app:latest
  expose:
    - 80
  links:
    - db 

db:
  image: postgres:latest

这个组合文件定义了两个服务,webdb

当你 运行 docker-compose up 时,假设项目目录是 test1 那么 compose 将启动 2 个名为 test1_db_1test1_web_1 的容器。

$ docker ps -a
CONTAINER ID   IMAGE        COMMAND          ...      NAMES
1c1683e871dc   test1_web    "nginx -g"       ...      test1_web_1
a41360558f96   test1_db     "postgres -d"    ...      test1_db_1

所以,此时您有 2 个服务和每个 1 个容器。

但是您可以扩展名为 web 的服务以使用 5 个容器。

$ docker-compose scale web=5
Creating and starting 2 ... done
Creating and starting 3 ... done
Creating and starting 4 ... done
Creating and starting 5 ... done

此时你有 2 个服务和 6 个容器

$ docker ps -a  
CONTAINER ID   IMAGE        COMMAND         ...      NAMES
1bf4c939263f   test1_web    "nginx -g"      ...      test1_web_3
d3033964a44b   test1_web    "nginx -g"      ...      test1_web_4
649bbda4d0b0   test1_web    "nginx -g"      ...      test1_web_5
a265ea406727   test1_web    "nginx -g"      ...      test1_web_2
1c1683e871dc   test1_web    "nginx -g"      ...      test1_web_1
a41360558f96   test1_db     "postgres -d'   ...      test1_db_1

此外,使用 docker-compose 您可以 运行 针对一项或多项服务的子命令。

$docker-compose stop web