--- title: 【軟體】Dockerfile 細節 tags: TTennis Pickup Robot disqus: hackmd --- <h1 style="text-align: center; color: orange;"> 🛠️ 【軟體】必學的 Docker 🛠️ </h1> <h2 style="text-align: center; color: skyblue;">Dockerfile 細節</h2> <h3><font color ="magenza">1. 開頭 & 結尾 & 註解 </font></h3> * 直上範例: ```dockerfile= ################################################################################################ # - Base stage # - This stage serves as the foundational stage for all other stages. # - Base image: OSRF ROS Humble Desktop Full # - https://hub.docker.com/r/osrf/ros/tags?page=1&name=humble-desktop-full ################################################################################################ FROM osrf/ros:humble-desktop-full LABEL org.opencontainers.image.authors="yoseph.huang@gmail.com" # .. # .. # .. CMD ["/bin/bash"] ``` * 在開頭使用 `LABEL` 標籤註明是誰在維護此 Docker Image。 * 註解越清楚越好,例如說明功能及用途、附上 Base Image 連結等。 * `CMD ["/bin/bash"]`:容器預設執行終端程序。 </br> <h3><font color ="magenza">2. 容量優化 </font></h3> Dockerfile 確定基本環境運作後,再來就要盡可能<font color="yellow">降低容量</font>。 > ![image](https://hackmd.io/_uploads/HJs-Prd5R.png =85%x) 這是我畢專用到的 Image,包含官方環境和自己疊加的。 這些映像檔容量全加起來不容小覷,若沒針對容量優化會很可怕。 </br> 1. <font color="yellow">安裝 package 後清除 APT 緩存列表。</font> ```dockerfile= RUN DEBIAN_FRONTEND=noninteractive apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y \ apt-utils \ git \ nano \ net-tools \ ssh \ usbutils \ udev \ x11-apps \ && rm -rf /var/lib/apt/lists/* ## 清除 APT 緩存 ``` 另外,`DEBIAN_FRONTEND=noninteractive` 是為了避免某些 package 在安裝時會跳出對話框請用戶做些設定,例如設定時區等等。 </br> 2. <font color="yellow">使用 Multi-stage Build。</font> 非常重要的技巧之一,筆記拉到這裡。 </br> <h3><font color ="magenza">3. Git Repo 版本 </font></h3> Dockerfile 有下載 Github 上的 Repo 時,記得鎖定 Branch 或 Tag,更保險是指定 commit 版本號。這是因為作者可能會更新 Repo,進而導致同一份 Dockerfile 在不同的時間點構建出來的環境不一樣。 * 參考範例: ```dockerfile= WORKDIR /home/realsense-ws/src RUN git clone --branch 0.3.7 https://github.com/ros-drivers/usb_cam.git && \ git clone --branch noetic https://github.com/ros-perception/image_pipeline.git && \ git clone --branch kinetic-devel https://github.com/pal-robotics/ddynamic_reconfigure.git && \ git clone --branch ros1-legacy --single-branch https://github.com/IntelRealSense/realsense-ros.git && \ (cd realsense-ros && git checkout $(git tag | sort -V | grep -P "^2.\\d+\\.\\d+" | tail -1)) && \ rm -rf .git ``` </br>