如何偵測LXC容器系統是否準備就緒?

如何偵測LXC容器系統是否準備就緒?

我正在嘗試啟動 LXC 容器,然後在其中執行命令。問題在於,即使容器處於 RUNNING 狀態,它也沒有完成所有的啟動。這會給 /tmp 帶來麻煩(我猜,還有其他初始化)。

這可以透過建立容器、啟動容器、等待其 RUNNING 狀態並執行一些命令的呼叫序列來說明;這些指令會建立一個檔案 /tmp/hello,顯示一個目錄,等一下,然後再顯示該目錄:

lxc-clone -B overlayfs -s -o vm -n c1 ; lxc-start -n c1 ; lxc-wait -n c1 -s RUNNING ; lxc-attach -n c1 -- su -c "touch /tmp/hello; ls -la /tmp; sleep 5; ls -la /tmp" slave ; lxc-stop -n c1 ; lxc-destroy -n c1

其輸出是

Created container c1 as snapshot of vm total 16 drwxrwxrwt 1 root root 4096 May 24 09:37 . drwxr-xr-x 1 root nogroup 4096 May 24 09:37 .. drwxrwxrwt 2 root root 4096 May 22 21:19 .ICE-unix drwxrwxrwt 2 root root 4096 May 22 21:19 .X11-unix -rw-rw-r-- 1 slave slave 0 May 24 09:37 hello total 16 drwxrwxrwt 1 root root 4096 May 24 09:37 . drwxr-xr-x 1 root nogroup 4096 May 24 09:37 .. drwxrwxrwt 2 root root 4096 May 24 09:37 .ICE-unix drwxrwxrwt 2 root root 4096 May 24 09:37 .X11-unix

並顯示檔案 /tmp/hello 被某些初始化腳本刪除。

如何在容器內等待系統完全啟動?另外,如何從容器外部執行此操作?

答案1

對於在 systemd 上運行的容器,這似乎效果很好:

lxc-attach -n [CONTAINER NAME] -- systemctl isolate multi-user.target

sysvinit您可能可以對基於或的容器應用相同的邏輯upstart(運行一個命令,該命令會阻塞,直到達到運行級別),但我無法立即告訴您哪些命令可以做到這一點。

答案2

就我而言,我認為 LXC 容器在具有網路連線時就處於「就緒」狀態(例如,這樣的命令apt update將在 LXC 容器設定腳本中運行)。

在 Debian 11 bullseye 作為 lxc 主機上,使用 Debian 11 bullseye lxc 容器,我成功地利用了以下模式:

lxc-unpriv-start -n "$LXC_CONTAINER"

lxc-wait -n "$LXC_CONTAINER" -s RUNNING
# the lxc-wait RUNNING state is not that useful;
# a container is already considered RUNNING even though the network is not yet up

# the following command blocks until the container's network is up
lxc-unpriv-attach -n "$LXC_CONTAINER" -- systemctl start systemd-networkd-wait-online.service

# when the script reaches this part, the lxc container's network probably is completely up and running

lxc-unpriv-attach -n "$LXC_CONTAINER" -- apt update
# ...

相關systemctl start systemd-networkd-wait-online.service部分: systemd-networkd-wait-online.service是一個開箱即用的 systemd 服務,只需要network-online.target(至少我是這麼理解的)。

因此,執行會systemctl start systemd-networkd-wait-online.service阻塞,直到網路啟動為止。

相關內容