--- tags: Docker --- # Control startup order in Docker-compose ##### keywords: `Docker` `Docker-compose` `wait-for-it.sh` > [name=Mr. Akashic] [time=Thu, Aug 12, 2021] ## Implementation 1. 下載官方推薦的[wait-for-it.sh](https://github.com/vishnubob/wait-for-it)檔案,只下載`wait-for-it.sh`。 2. 使用Dockerfile的方式,將`wait-for-it.sh`複製到現有的image,並產生新的image。如下指令。 ```bash= # Copy wait-for-it.sh to container COPY wait-for-it.sh /application/wait-for-it.sh RUN chmod +x /application/wait-for-it.sh ``` 完整操作可參考[Creating a new image from an existing container with a Dockerfile](https://hackmd.io/@JGoK5hXkSQuAC32KMw8hHw/B1di8OPju)。 3. 在docker-compose.yml檔案內,在要等待的服務中加入`entrypoint`標籤,範例內容如下。在bt-mqtt-gateway服務中加入`entrypoint`標籤。 ```yaml= bt-mqtt-gateway: container_name: bt-mqtt-gateway image: akashic0616/bt-mqtt-gateway:latest restart: always devices: # the value of "/dev/input/" corresponds to an actual path on the system of Raspberry Pi 4. - /dev/input:/dev/input volumes: - /etc/localtime:/etc/localtime:ro - /opt/bt-mqtt-gateway/config.yaml:/config.yaml cap_add: - NET_ADMIN - SYS_ADMIN - SYS_RESOURCE network_mode: host entrypoint: ["/application/wait-for-it.sh", "127.0.0.1:8123", "--timeout=0", "--", "/bin/sh", "-c", "/start.sh" ] depends_on: - mosquitto - hassio ``` entrypoint標籤,參數設定說明: * `/application/wait-for-it.sh`:執行wait-for-it.sh檔案,檔案位置在container內的在application資料夾。 * `127.0.0.1:8123`:表示等待127.0.0.1:8123的服務啟動了,才啟動bt-mqtt-gateway服務。 * `--timeout=0`:等待多久的時間,0表示一直等待。 * `--`:表示等待的時間到了,執行`/bin/sh -c /start.sh`(subcommand)。若不執行就設為`--strict`模式。 * `/bin/sh -c /start.sh`:執行start.sh檔案,啟動bt-mqtt-gateway服務。 這樣就完成了本篇記錄的實作,執行`docker-compose up -d`指令後,就會依照設定方式先後執行服務,[完整範例](https://github.com/awlchang/Creating-a-new-image-from-an-existing-container-with-a-Dockerfile.git)。 ## Introduction 通常若要啟動多個服務的docker container,會統一將這些服務寫在一個docker-compose.yml檔案,而這些服務在啟動時可能會有先後順序,才能順利運作。較常看到的例子就是要先啟動資料庫的服務,之後才前端Web應用程式的服務,避免造成前端Web應用程式抓不到資料庫資料,而無法正常顯示訊息給使用者,因此本篇記錄如何使用wait-for-it.sh的檔案,來控制服務啟動的順序。 ## Acknowledgements [Control startup and shutdown order in Compose](https://docs.docker.com/compose/startup-order/) [vishnubob/wait-for-it](https://github.com/vishnubob/wait-for-it) <style> .dark_orange { color: #FF8C00; background:#F6F6F6; border-radius:4px; padding-right:6px; padding-left:6px; } .sub_title { font-size: 25px; } .blockquote { background:#F6F6F6; } </style>