服务和容器之间有关联但是它们是不同的东西。
一个服务可以由一个或多个容器运行。使用 docker
可以处理容器,使用 docker-compose
可以处理服务。
比如:
假设我们有这个 docker-compose.yml
文件:
web:
image: example/my_web_app:latest
expose:
- 80
links:
- db
db:
image: postgres:latest
这个 compose 文件定义了两个服务,web
和 db
。
当你运行 docker-compose up
命令时,假设项目文件夹名为 test1
,compose 将会启动 2 个容器,分别命名为 test1_db_1
和 test1_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