docker-compose service name和container name的關系
問題
我們在定義docker-compose.yaml文件里面經(jīng)常會有service name和container name,這兩者有什么關系呢?
$ cat docker-compose.yaml
version: '2'
networks:
mynet:
services:
linuxservice:
image: oraclelinux
container_name: linuxservice.example.com
command: sleep 5000
networks:
- mynet
基本概念
- 一個service可以擁有一個或多個container伏伯。
- container是docker的概念,因此我們在docker域里面乖菱,處理的是container。
- service是docker-compose概念抗悍, 因此我們在docker-compose域里面吃嘿,才處理的是service。(當然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沒有定義
$ cat docker-compose.yaml
version: '2'
networks:
mynet:
services:
linuxservice:
image: oraclelinux
#container_name: linuxservice.example.com
command: sleep 5000
networks:
- mynet
起來之后:
$ 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自動給container分配了一個名字琴锭,其格式為:<當前工作路徑名>_<servicename>_<sequencenumber>晰甚。
sequencenumber是干什么用的呢,我們看后面的例子决帖。
例子2:一個service包含多個container
我們一次啟動5個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
這個例子中我們看到service有5個container被創(chuàng)建出來厕九,每一container的sequence是從1開始累加。
注意:
- 前面的docker-compose stop/start會對5個container一起操作地回。
- 此時就不能指定container name扁远,因為不能5個container使用同樣的container name。