Docker-Compose學習使用
轉載請註明出處: Docker-Compose學習使用
docker
1. 什麼是docker-compose
Docker Compose是一個用來定義和運行復雜應用的Docker工具。一個使用Docker容器的應用,通常由多個容器組成。使用Docker Compose不再需要使用shell指令碼來啟動容器。
Compose 通過一個配置檔案來管理多個Docker容器,在配置檔案中,所有的容器通過services來定義,然後使用docker-compose指令碼來啟動,停止和重啟應用,和應用中的服務以及所有依賴服務的容器,非常適合組合使用多個容器進行開發的場景。
2. 安裝
docker-compose安裝可以參考官方文件: Install Docker Compose
2.1. macOs
Docker Desktop for Mac
和 Docker Toolbox
已集成了docker-compose, 所以只要安裝了docker是不需要安裝的,直接就可以用。
2.2. Linux
在Linux系統中,可以通過原始碼來安裝docker-compose
- 從github下載最新版docker-compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
- 給docker-compose賦予可執行許可權
sudo chmod +x /usr/local/bin/docker-compose
最後可以通過以下命令來驗證是否安裝成功:
docker-compose --version
3. 語法
docker-compose 檔案命名以 .yml
或 .yaml
為字尾。
下面先欣賞一下官方文件中的一個示例:
version: "3" services: redis: image: redis:alpine ports: - "6379" networks: - frontend deploy: replicas: 2 update_config: parallelism: 2 delay: 10s restart_policy: condition: on-failure db: image: postgres:9.4 volumes: - db-data:/var/lib/postgresql/data networks: - backend deploy: placement: constraints: [node.role == manager] vote: image: dockersamples/examplevotingapp_vote:before ports: - "5000:80" networks: - frontend depends_on: - redis deploy: replicas: 2 update_config: parallelism: 2 restart_policy: condition: on-failure result: image: dockersamples/examplevotingapp_result:before ports: - "5001:80" networks: - backend depends_on: - db deploy: replicas: 1 update_config: parallelism: 2 delay: 10s restart_policy: condition: on-failure worker: image: dockersamples/examplevotingapp_worker networks: - frontend - backend deploy: mode: replicated replicas: 1 labels: [APP=VOTING] restart_policy: condition: on-failure delay: 10s max_attempts: 3 window: 120s placement: constraints: [node.role == manager] visualizer: image: dockersamples/visualizer:stable ports: - "8080:8080" stop_grace_period: 1m30s volumes: - "/var/run/docker.sock:/var/run/docker.sock" deploy: placement: constraints: [node.role == manager] networks: frontend: backend: volumes: db-data:
從上述示例看,整個文件分為4部分, version
, services
, networks
, volumes
, 其中 services
中內容最長,下面將一一做個簡單介紹
3.1. version
version是compose的版本,下表是compose版本與docker版本對照表:
Compose file format | Docker Engine release |
---|---|
3.7 | 18.06.0+ |
3.6 | 18.02.0+ |
3.5 | 17.12.0+ |
3.4 | 17.09.0+ |
3.3 | 17.06.0+ |
3.2 | 17.04.0+ |
3.1 | 1.13.1+ |
3.0 | 1.13.0+ |
2.4 | 17.12.0+ |
2.3 | 17.06.0+ |
2.2 | 1.13.0+ |
2.1 | 1.12.0+ |
2.0 | 1.10.0+ |
1.0 | 1.9.1.+ |
3.2. services
services是用來配置定義每個容器啟動引數,每個service就是一個容器,services下一級配置即是服務名稱,例如上面示例中的redis, db等。
3.2.1. image
image是指定服務的映象名稱或映象 ID。如果映象在本地不存在,Compose 將會嘗試拉取這個映象。
例如下面這些格式都是可以的:
image: redis image: ubuntu:14.04 image: tutum/influxdb image: example-registry.com:4000/postgresql image: a4bc65fd
3.2.2. build
服務除了可以基於指定的映象,還可以基於一份 Dockerfile,在使用 up 啟動之時執行構建任務,這個構建標籤就是 build,它可以指定 Dockerfile 所在資料夾的路徑。Compose 將會利用它自動構建這個映象,然後使用這個映象啟動服務容器。
build: /path/to/build/dir
也可以是相對路徑,只要上下文確定就可以讀取到 Dockerfile。
build: ./dir
設定上下文根目錄,然後以該目錄為準指定 Dockerfile。
build: context: ../ dockerfile: path/of/Dockerfile
注意 build 都是一個目錄,如果你要指定 Dockerfile 檔案需要在 build 標籤的子級標籤中使用 dockerfile 標籤指定,如上面的例子。
如果你同時指定了 image 和 build 兩個標籤,那麼 Compose 會構建映象並且把映象命名為 image 後面的那個名字。
既然可以在 docker-compose.yml 中定義構建任務,那麼一定少不了 arg 這個標籤,就像 Dockerfile 中的 ARG 指令,它可以在構建過程中指定環境變數,但是在構建成功後取消,在 docker-compose.yml 檔案中也支援這樣的寫法:
build: context: . args: buildno: 1 password: secret
下面這種寫法也是支援的,一般來說下面的寫法更適合閱讀。
build: context: . args: - buildno=1 - password=secret
與 ENV 不同的是,ARG 是允許空值的。例如:
args: - buildno - password
這樣構建過程可以向它們賦值。
注意:YAML 的布林值(true, false, yes, no, on, off)必須要使用引號引起來(單引號、雙引號均可),否則會當成字串解析。
3.2.3. command
使用 command 可以覆蓋容器啟動後預設執行的命令。
command: bundle exec thin -p 3000
也可以寫成類似 Dockerfile 中的格式:
command: [bundle, exec, thin, -p, 3000]
3.2.4. container_name
Compose 的容器名稱格式是:<專案名稱><服務名稱><序號>
雖然可以自定義專案名稱、服務名稱,但是如果你想完全控制容器的命名,可以使用這個標籤指定:
container_name: app
這樣容器的名字就指定為 app 了。
3.2.5. depends_on
在使用 Compose 時,最大的好處就是少打啟動命令,但是一般專案容器啟動的順序是有要求的,如果直接從上到下啟動容器,必然會因為容器依賴問題而啟動失敗。
例如在沒啟動資料庫容器的時候啟動了應用容器,這時候應用容器會因為找不到資料庫而退出,為了避免這種情況我們需要加入一個標籤,就是 depends_on,這個標籤解決了容器的依賴、啟動先後的問題。
例如下面容器會先啟動 redis 和 db 兩個服務,最後才啟動 web 服務:
version: '2' services: web: build: . depends_on: - db - redis redis: image: redis db: image: postgres
注意的是,預設情況下使用 docker-compose up web 這樣的方式啟動 web 服務時,也會啟動 redis 和 db 兩個服務,因為在配置檔案中定義了依賴關係。
3.2.6.dns
和 --dns 引數一樣用途,格式如下:
dns: 8.8.8.8
也可以是一個列表:
dns: - 8.8.8.8 - 9.9.9.9
此外 dns_search 的配置也類似:
dns_search: example.com dns_search: - dc1.example.com - dc2.example.com
3.2.7. environment
和 arg 有幾分類似,這個標籤的作用是設定映象變數,它可以儲存變數到映象裡面,也就是說啟動的容器也會包含這些變數設定,這是與 arg 最大的不同。
一般 arg 標籤的變數僅用在構建過程中。而 environment 和 Dockerfile 中的 ENV 指令一樣會把變數一直儲存在映象、容器中,類似 docker run -e 的效果。
environment: RACK_ENV: development SHOW: 'true' SESSION_SECRET: environment: - RACK_ENV=development - SHOW=true - SESSION_SECRET
3.2.8. extra_hosts
新增主機名的標籤,就是往/etc/hosts檔案中新增一些記錄,與Docker client的--add-host類似:
extra_hosts: - "somehost:162.242.195.82" - "otherhost:50.31.209.229"
啟動之後檢視容器內部hosts:
162.242.195.82somehost 50.31.209.229otherhost
3.2.9. labels
向容器新增元資料,和Dockerfile的LABEL指令一個意思,格式如下:
labels: com.example.description: "Accounting webapp" com.example.department: "Finance" com.example.label-with-empty-value: "" labels: - "com.example.description=Accounting webapp" - "com.example.department=Finance" - "com.example.label-with-empty-value"
3.2.10 links
還記得上面的depends_on吧,那個標籤解決的是啟動順序問題,這個標籤解決的是容器連線問題,與Docker client的--link一樣效果,會連線到其它服務中的容器。
格式如下:
links: - db - db:database - redis
使用的別名將會自動在服務容器中的/etc/hosts裡建立。例如:
172.12.2.186db 172.12.2.186database 172.12.2.187redis
相應的環境變數也將被建立。
3.2.11 ports
對映埠的標籤。
使用HOST:CONTAINER格式或者只是指定容器的埠,宿主機會隨機對映埠。
ports: - "3000" - "8000:8000" - "49100:22" - "127.0.0.1:8001:8001"
注意:當使用HOST:CONTAINER格式來對映埠時,如果你使用的容器埠小於60你可能會得到錯誤得結果,因為YAML將會解析xx:yy這種數字格式為60進位制。所以建議採用字串格式。
3.2.12. volumes
掛載一個目錄或者一個已存在的資料卷容器,可以直接使用 [HOST:CONTAINER] 這樣的格式,或者使用 [HOST:CONTAINER:ro] 這樣的格式,後者對於容器來說,資料卷是隻讀的,這樣可以有效保護宿主機的檔案系統。
Compose的資料卷指定路徑可以是相對路徑,使用 . 或者 .. 來指定相對目錄。
資料卷的格式可以是下面多種形式:
volumes: // 只是指定一個路徑,Docker 會自動在建立一個數據卷(這個路徑是容器內部的)。 - /var/lib/mysql // 使用絕對路徑掛載資料卷 - /opt/data:/var/lib/mysql // 以 Compose 配置檔案為中心的相對路徑作為資料卷掛載到容器。 - ./cache:/tmp/cache // 使用使用者的相對路徑(~/ 表示的目錄是 /home/<使用者目錄>/ 或者 /root/)。 - ~/configs:/etc/configs/:ro // 已經存在的命名的資料卷。 - datavolume:/var/lib/mysql
如果你不使用宿主機的路徑,你可以指定一個volume_driver。
volume_driver: mydriver
3.2.13. networks
加入指定網路,格式如下:
services: some-service: networks: - some-network - other-network
關於這個標籤還有一個特別的子標籤aliases,這是一個用來設定服務別名的標籤,例如:
services: some-service: networks: some-network: aliases: - alias1 - alias3 other-network: aliases: - alias2
相同的服務可以在不同的網路有不同的別名。
3.2.14. network_mode
網路模式,與Docker client的--net引數類似,只是相對多了一個service:[service name] 的格式。
例如:
network_mode: "bridge" network_mode: "host" network_mode: "none" network_mode: "service:[service name]" network_mode: "container:[container name/id]"
可以指定使用服務或者容器的網路。
4. 常用命令
docker-compose常用命令可以通過以下命令大致看一下:
docker-compose --help
結果如下:
Define and run multi-container applications with Docker. Usage: docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...] docker-compose -h|--help Options: -f, --file FILESpecify an alternate compose file (default: docker-compose.yml) -p, --project-name NAMESpecify an alternate project name (default: directory name) --verboseShow more output --log-level LEVELSet log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) --no-ansiDo not print ANSI control characters -v, --versionPrint version and exit -H, --host HOSTDaemon socket to connect to --tlsUse TLS; implied by --tlsverify --tlscacert CA_PATHTrust certs signed only by this CA --tlscert CLIENT_CERT_PATHPath to TLS certificate file --tlskey TLS_KEY_PATHPath to TLS key file --tlsverifyUse TLS and verify the remote --skip-hostname-checkDon't check the daemon's hostname against the name specified in the client certificate --project-directory PATHSpecify an alternate working directory (default: the path of the Compose file) --compatibilityIf set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent Commands: buildBuild or rebuild services bundleGenerate a Docker bundle from the Compose file configValidate and view the Compose file createCreate services downStop and remove containers, networks, images, and volumes eventsReceive real time events from containers execExecute a command in a running container helpGet help on a command imagesList images killKill containers logsView output from containers pausePause services portPrint the public port for a port binding psList containers pullPull service images pushPush service images restartRestart services rmRemove stopped containers runRun a one-off command scaleSet number of containers for a service startStart services stopStop services topDisplay the running processes unpauseUnpause services upCreate and start containers versionShow the Docker-Compose version information
下面會針對一些比較常用的命令進行簡單介紹
4.1. build
當修改dockerfile或者docker-compose時,執行docker-compose build 重建映象。 生成映象後,可使用docker-compose up啟動
4.2. ps
顯示所有容器資訊,預設顯示name、command、state、ports。
4.3. kill
強制停止某個正在執行的服務
4.4. logs
列印服務日誌
語法:
logs [options] [SERVICE...]
引數:
--no-colorProduce monochrome output. -f, --followFollow log output -t, --timestampsShow timestamps --tail="all"Number of lines to show from the end of the logs for each container.
4.5. up
構建,(重新)建立,啟動,連結一個服務相關的容器。連結的服務都將會啟動,除非他們已經執行。預設情況, docker-compose up
將會整合所有容器的輸出,並且退出時,所有容器將會停止。如果使用 docker-compose up -d
,將會在後臺啟動並執行所有的容器。
預設情況,如果該服務的容器已經存在, docker-compose up
將會停止並嘗試重新建立他們(保持使用 volumes-from
掛載的卷),以保證 docker-compose.yml的修改生效。如果你不想容器被停止並重新建立,可以使用 docker-compose up --no-recreate
。如果需要的話,這樣將會啟動已經停止的容器。
語法:
up [options] [--scale SERVICE=NUM...] [SERVICE...]
引數:
-d後臺執行,輸出容器的名字. Incompatible with --abort-on-container-exit. --no-color單色輸出. --no-deps不啟動link服務. --force-recreate強制重新建立compose服務,即使沒有任何改變。重新建立後啟動容器 Incompatible with --no-recreate. --no-recreate如果容器已經存在,不重新建立. Incompatible with --force-recreate. --no-build不建立重啟,即使映象不存在. --build重新建立映象,然後生成容器. --abort-on-container-exit任何容器停止,自動停止所有容器. Incompatible with -d. -t, --timeout TIMEOUT超時時間. (default: 10) --remove-orphans移除compose檔案中未定義服務的容器
4.6. create
為服務建立容器.只是單純的create,還需要使用start啟動compose
語法:
create [options] [SERVICE...]
引數
--force-recreate重新建立容器,即使他的配置和映象沒有改變,不相容--no-recreate引數 --no-recreate如果容器已經存在,不需要重新建立. 不相容--force-recreate引數 --no-build不建立映象,即使缺失. --build建立容器前,生成映象
4.7. down
停止和刪除容器、網路、卷、映象,這些內容是通過 docker-compose up
命令建立的. 預設值刪除容器網路,可以通過指定 rmi volumes
引數刪除映象和卷。
語法:
down [options]
引數:
--rmi type刪除映象,型別必須是: 'all': 刪除compose檔案中定義的所以映象. 'local': 刪除映象名為空的映象 -v, --volumes刪除卷 attached to containers. --remove-orphansRemove containers for services not defined in the Compose file
4.8. start
啟動一個已經存在的服務容器。
4.9. stop
停止一個已經執行的容器,但不刪除它。通過 docker-compose start
可以再次啟動這些容器。
4.10. pause
暫停容器服務, docker-compose pause
暫停所有服務。 docker-compose pause web
,暫停web服務的容器。
4.11. unpause
恢復容器服務, docker-compose unpause
恢復所有服務, docker-compose unpause web
,恢復web服務的容器。
4.12. restart
重啟docker-compose.yml中定義的所有的已停止的和正在執行的服務。
4.13. rm
刪除已經停止的容器,如果服務在執行,需要先 docker-compose stop
停止容器,預設情況下,已掛載的volume中的資料不會被刪除,可以使用 docker volume ls
檢視所有的volume情況。所有在容器中並未在volume中的資料將被刪除。
4.14. run
在一個服務上執行一個命令.
語法:
run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] SERVICE [COMMAND] [ARGS...]
引數:
-d後臺執行,輸出容器名. -e KEY=VAL設定環境變數引數,可以使用多次 -u, --user=""指定執行的使用者 --no-deps不啟動link服務,只啟動run的服務. --rm執行後刪除容器,後臺執行模式除外(-d). -p, --publish=[]開放埠 --service-portscompose檔案中配置什麼埠,就對映什麼埠. -T禁用TTY. -w, --workdir=""設定工作目錄
例如:
docker-compose run ubuntu ping docker.com
4.15. scale
設定同一個服務執行的容器個數。通過 service=num 的引數來設定數量。
5. 參考文件
完
轉載請註明出處: Docker-Compose學習使用