Docker Compose

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Docker Compose 是一個用於定義和運行多容器應用的工具,利用 yaml 文件來配置所需要的所有服務,可以同時啟動多個容器並建立容器之間的關聯。

安裝

安裝方式依照不同作業系統可以在 Docker 官網 找到相對應的安裝方式,以下以 linux 為例 :

  1. 下載 Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.25.5/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  1. 修改執行權限
sudo chmod +x /usr/local/bin/docker-compose
  1. 測式安裝是否成功
docker-compose --version

建立 docker-compose.yml

範例 :

這個範例啟動了兩個 Container,分別為 app1 和 app2,若是一般專案設定可以像範例的 app1 設定即可,其他設定到 CI、CD 再設定會比較好。

version: '3' services: app1: image: imageName build: context: . dockerfile: dockerfilePath/Dockerfile app2: image: imageName

yml配置指令

version
指定yml使用哪個版本的 compose

build
兩種方式

  1. 指定建立 image 的路徑,例如 : build: ./dir,Dockerfile 在 ./dir 路徑下
version: '3' services: app1: image: imageName build: ./dockerfilePath
  1. 設定 Dockerfile 路徑,並選擇 Dockerfile,通常是因為有自定義不同名稱的 Dockerfile 才需要特別指定 Dockerfile
  • context : 上下文路徑
  • dockerfile : 指定 Dockerfile
  • args : 添加建置參數,只能在建置過程中存取的環境變數
  • labels : 建置 image 的標籤
  • target : 多層建置,指定建置哪一層
version: '3' services: app1: image: imageName build: context: . dockerfile: dockerfilePath/Dockerfile args: buildConfig: Debug labels: - "exmaple.com.lable1" - "example.com.label2" target: prod

environment
添加環境變數,若要使用 boolean 需要用單引號括起來,否則 yml 解析器不會解析為 boolean

environment: ASPNETCORE_ENVIRONMENT: Development SHOW: 'true'

expose
暴露端口,Container 內部開放存取的 Port 號。expose 用於讓 Container 互相溝通,像是 redis 就有 expose port 6379 來讓 Container 之間互相溝通。

expose: - "9890" - "9875"

ports
Port 對應,Host Port : Container Expose Port

ports: - 9878:80 - 9876:443 - 9898:9898

network_mode
設置網路模式,bridge、host,等。

network_mode: "bridge"

restart
設置重啟策略,預設是 no
always : 總是重啟
on-failure : container 正常退出時(退出狀態非0)才重啟

restart: "no" restart: always restart: on-failure

secrets
儲存敏感數據,例如密碼

secrets: my_secret: file: ./my_secret.txt

volumes
將主機的文件掛載到 Container

volumes: - "/localhost/data:/var/lib/postgresql/data1" - "/localhost/data:/var/lib/postgresql/data2"

depends_on
設定啟動順序,docker compose 可以一次啟動多個 Container,但是有些 Container 之間是有關連性的就必須有順序性的啟動。

version: '3' services: master: image: redis container_name: redis-master ports: - 6379:6379 volumes: - ./node/redis-master.conf:/usr/local/etc/redis/redis.conf slave1: image: redis container_name: redis-slave1 ports: - 6380:6379 volumes: - ./node/redis-master.conf:/usr/local/etc/redis/redis.conf depends_on: - master

以上列出較常用到指令,其他見參考3

啟動 docker compose 中所定義的所有 image 成 container

-d : 背景執行

docker-compose up -d

參考

[1] 用 Docker-Compose 啟動多個 Docker Container
[2] Install Docker Compose
[3] Docker Compose | Runoob.com
[4] Understanding “EXPOSE”

tags:Container Docker