docker-compose service name和container name的關(guān)系
問(wèn)題
我們?cè)诙xdocker-compose.yaml文件里面經(jīng)常會(huì)有service name和container name,這兩者有什么關(guān)系呢?
$ cat docker-compose.yaml
version: '2'
networks:
mynet:
services:
linuxservice:
image: oraclelinux
container_name: linuxservice.example.com
command: sleep 5000
networks:
- mynet
基本概念
- 一個(gè)service可以擁有一個(gè)或多個(gè)container。
- container是docker的概念,因此我們?cè)赿ocker域里面,處理的是container。
- service是docker-compose概念, 因此我們?cè)赿ocker-compose域里面,才處理的是service。(當(dāng)然docker-compose也能處理container)。
以上述為例:
$ docker-compose up
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
94e6bc9e06a6 oraclelinux "sleep 5000" 17 seconds ago Up 15 seconds linuxservice.example.com
$ docker-compose stop linuxservice
Stopping linuxservice.example.com ... done
$ docker-compose start linuxservice
Starting linuxservice ... done
$ docker-compose stop linuxservice.example.com
ERROR: No such service: linuxservice.example.com
$ docker-compose start linuxservice.example.com
ERROR: No such service: linuxservice.example.com
我們可以看到docker-compose start/stop處理的service name,而不是container name。
例子1:如果container name沒(méi)有定義
$ cat docker-compose.yaml
version: '2'
networks:
mynet:
services:
linuxservice:
image: oraclelinux
#container_name: linuxservice.example.com
command: sleep 5000
networks:
- mynet
起來(lái)之后:
$ docker-compose up
Creating network "test_mynet" with the default driver
Creating test_linuxservice_1 ... done
Attaching to test_linuxservice_1
$ docker-compose ps
Name Command State Ports
------------------------------------------------
test_linuxservice_1 sleep 5000 Up
我們看到docker-compose自動(dòng)給container分配了一個(gè)名字,其格式為:<當(dāng)前工作路徑名>_<servicename>_<sequencenumber>。
sequencenumber是干什么用的呢,我們看后面的例子。
例子2:一個(gè)service包含多個(gè)container
我們一次啟動(dòng)5個(gè)linuxservice containers:
$ docker-compose up --scale linuxservice=5
Creating test_linuxservice_1 ... done
Creating test_linuxservice_2 ... done
Creating test_linuxservice_3 ... done
Creating test_linuxservice_4 ... done
Creating test_linuxservice_5 ... done
Attaching to test_linuxservice_1, test_linuxservice_3, test_linuxservice_2, test_linuxservice_5, test_linuxservice_4
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
111c825dba18 oraclelinux "sleep 5000" 38 seconds ago Up 33 seconds test_linuxservice_4
c5a555dd53aa oraclelinux "sleep 5000" 39 seconds ago Up 33 seconds test_linuxservice_5
76b377abf70a oraclelinux "sleep 5000" 39 seconds ago Up 34 seconds test_linuxservice_2
ec5e33032dd0 oraclelinux "sleep 5000" 39 seconds ago Up 35 seconds test_linuxservice_3
b15cf589db88 oraclelinux "sleep 5000" 39 seconds ago Up 37 seconds test_linuxservice_1
這個(gè)例子中我們看到service有5個(gè)container被創(chuàng)建出來(lái),每一container的sequence是從1開始累加。
注意:
- 前面的docker-compose stop/start會(huì)對(duì)5個(gè)container一起操作。
- 此時(shí)就不能指定container name,因?yàn)椴荒?個(gè)container使用同樣的container name。