Docker用法總結(二)compose文件

書接上文,上一篇介紹了dockerfiledocker-compose的關係,以及dockerfile中的常用指令。本篇將介紹docker-compose文件的寫法。

Compose file

Docker-compose.yml是主要用於啓動docker容器的配置文件,yaml格式,簡單講就配置容器怎樣啓動,比如使用哪個鏡像、怎樣映射端口、如何掛載volume,執行什麼命令等等,相當於docker run的參數配置文件。

docker-compose命令根據Docker-compose.yml的內容生成鏡像或管理容器(開啓/停止/重啓/查看/刪除…)

此外,Docker-compose還可以用來定義和運行由多個容器組成的應用。

Define and run multi-container applications with Docker
https://docs.docker.com/compose/

格式

version: '3'
services:
  web:
    build: .
    ports:
    - "5000:5000"
    volumes:
    - .:/code
    - logvolume01:/var/log
    links:
    - redis
  redis:
    image: redis
volumes:
  logvolume01: {}

最開頭的是版本號,兼容性見下表

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.+

配置

compose文件中定義的內容包括services, networksvolumes
默認的compose文件爲./docker-compose.yml

services

容器的配置信息在services中定義。即:定義應用中包含的每個容器該如何啓動

image

定義容器使用的鏡像

version: "3"
services:
  webapp:
    image: redis:4
    # ...

build

定義通過docker-compose build命令創建鏡像時使用的Dockerfile

version: "3"
services:
  webapp:
    build: ./dir

通過build來定義Dockerfile所在的目錄

也可以通過以下的詳細配置,自定義Dockerfile:

version: "3"
services:
  webapp:
    build:
      context: ./dir
      dockerfile: Dockerfile-alternate
      args:
        buildno: 1

其中args是在Dockerfile中定義的變量,比如:

ARG buildno
ARG gitcommithash

RUN echo "Build number: $buildno"
RUN echo "Based on commit: $gitcommithash"

另一種定義格式:

build:
  context: .
  args:
    - buildno=1

此外,buildimage可以一起使用,image用於定義生成的鏡像名

version: "3"
services:
  webapp:
    image: taqini/myapp
    build: ./dir

user

定義默認用戶

restart

定義容器掛掉後是否自動重啓

environment

定義環境變量

    environment:
      - UPLOAD_FOLDER=/var/uploads
      - WORKERS=1
      - LOG_FOLDER=/var/log/xxx
      - ACCESS_LOG=-
      - ERROR_LOG=-

volumes

定義掛載的數據卷

    volumes:
     - ./file/bin:/home/ctf:ro
     - ./file/config/motd:/etc/motd:ro
     - ./file/config/issue:/etc/issue:ro
     - ./file/config/legal:/etc/legal:ro

末尾加:ro可控制容器中數據卷權限爲只讀

若容器中存在同名文件(夾),本地文件將覆蓋容器中文件(夾)

注意:若覆蓋文件,文件權限也會覆蓋

掛載數據卷,可以使得容器與數據(應用程序數據、配置信息等等)分離,這樣在更新容器的時候不會丟失數據

ports

定義端口映射 本地:容器

    ports:
      - "10080:80"
      - "10022:22"

networks

定義網絡

command

定義容器默認執行的命令

格式和dockerfile差不多:

version: "3"
services:
  webapp:
    build: ./
    command: bundle exec thin -p 3000
    #command: ["bundle", "exec", "thin", "-p", "3000"]

compose中定義的command會覆蓋dockerfile中的CMD

entrypoint

和command類似,不多說了

Next

下一篇介紹docker命令和docker-compose命令

docker命令比較基礎,但是命令繁雜

docker-compose像是一個容器管理工具,用起來比較簡便

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章