Apple Container Machines: A Lightweight Linux Environment for macOS

Apple 已推出 Container Machines,這是一個高度整合的 Linux 環境,旨在於 macOS 上無縫運行。與傳統以應用程式為中心的容器不同,Container Machines 是模擬完整的 Linux 環境,允許開發者運行長期運行的服務、使用 systemd 等程序監督器,並維持持久化儲存。

Core Capabilities of Container Machines

Container Machines 透過整合主機檔案系統與使用者身分,在 macOS 與 Linux 開發之間架起橋樑。其主要目標是讓開發者能夠使用 macOS 原生工具進行編輯與除錯,同時在 Linux 環境中執行程式碼。

Integrated Filesystem and Identity

Container Machines 會自動將 macOS 主機的使用者名稱與家目錄映射到 Linux 環境中。這確保了儲存庫與 dotfiles 在兩個平台上皆可使用,而無需手動配置。

  • Edit on Mac, Build in Linux: macOS 上的 $HOME 目錄中的原始碼會被掛載到容器機內的 /Users/<username>,從而能夠在 Linux 中編譯與運行程式碼的同時,使用 macOS 的 IDE 與編輯器。
  • Native Tooling Access: 由於容器機與主機共享相同的檔案,macOS 原生的分析器 (profilers)、GUI 除錯器與瀏覽器可以直接檢查 Linux 的建置產物 (build artifacts),而無需經過複製步驟。

Environment Persistence and Service Management

與通常只運行單一程序的標準 OCI 容器不同,Container Machines 會運行映像檔的 init 系統。這讓開發者可以使用 systemctl 等工具(在安裝了 systemd 的映像檔上)來註冊與管理長期運行的系統服務。

Multi-Distribution Support

開發者可以根據不同的目標發行版(例如 Alpine, Ubuntu, Debian)建立多個容器機,以便在各種 Linux 發行版中測試應用程式,同時在所有發行版中維持相同的 $HOME 與 dotfiles。

Technical Implementation and Usage

Container Machines 是透過 container machine 命令列工具(別名為 m)進行管理的。

Quickstart and Basic Commands

若要建立並運行一個容器機,請使用以下工作流程:

container machine create alpine:latest --name dev
container machine run -n dev

關鍵管理命令包括:

  • container machine ls: 列出所有啟動中的容器機。
  • container machine stop dev: 停止特定的機器。
  • container machine rm dev: 刪除機器及其持久化儲存。
  • container machine set-default dev: 設定預設機器以省略 -n 參數。

Resource Configuration

可以使用 container machine set 命令來調整資源。變更會在重新啟動後生效:

container machine set -n dev cpus=4 memory=8G

記憶體預設為主機可用記憶體的一半。家目錄掛載 (home-mount) 可以配置為讀寫 (rw)、唯讀 (ro) 或停用 (none)。

Customizing Container Machine Images

任何包含 /sbin/init 的 Linux 映像檔都可以作為容器機使用。Apple 提供了一個包含 systemd 與常用 CLI 工具的 Ubuntu 24.04 Dockerfile 範例。

若要實作自定義使用者配置,開發者可以在映像檔中加入一個執行檔腳本於 /etc/machine/create-user.sh。此腳本會在首次啟動時以 root 身分運行,並可以存取環境變數,例如 CONTAINER_UIDCONTAINER_GIDCONTAINER_USER

Community Insights and Comparisons

Hacker News 上的開發者討論指出,Container Machines 正被拿來與 OrbStack、Colima、Lima、以及 Distrobox 等工具進行比較。

Architecture and Performance

一位使用者指出,根據技術文件確認,每個容器機都在其自身的 VM 中運行。這使其與 WSL1 等共享核心 (shared-kernel) 的方式有所不同。

Use Cases and Case Studies

開發者們強調了此工具的幾個潛在應用場景:

"Apple containers are great for providing a sandbox to your AI coding agents... I have made it a MCP so that it's easily discoverable by all"

Comparison to Existing Tools

一些使用者對 Apple 提供這款第一方解決方案的必要性提出了疑問,並指出現有的開源替代方案(如 Colima 或 QEMU/Lima)已提供類似的功能,包括相同的檔案系統掛載與 VM 管理。

Limitations

一些早期採用者回報了映像檔相容性問題,報告稱標準 Docker Hub 映像檔通常缺乏 Container Machines 運作所需的 systemd 要求。

Sources