服务和容器是相关的,但两者是不同的东西。
一项服务可以由一个或多个容器运行。
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会启动两个容器,分别命名为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