實戰演練:把一個網站容器化並用 systemd 管理
假設我們有一個簡單的靜態網站,目錄結構如下:
myblog/
├── Containerfile
└── public/
└── index.html
Containerfile 內容:
FROM docker.io/library/nginx:alpine
COPY public/ /usr/share/nginx/html/
EXPOSE 80
建置並測試:
podman build -t localhost/myblog:latest .
podman run -d --name myblog -p 8080:80 localhost/myblog:latest
curl http://localhost:8080
確認沒問題後,建立 Quadlet 設定檔 ~/.config/containers/systemd/myblog.container:
[Unit]
Description=My Blog
[Container]
Image=localhost/myblog:latest
PublishPort=8080:80
[Service]
Restart=always
[Install]
WantedBy=default.target
podman rm -f myblog # 移除手動跑的測試容器
systemctl --user daemon-reload
systemctl --user enable --now myblog
journalctl --user -u myblog -f
之後即使重開機,這個服務也會自動啟動。本站(高科隨聊)就是用類似的 Podman + Quadlet 架構部署的。
練習建議
- 試著修改
index.html後重新podman build,觀察哪些層會重新建置、哪些會用到快取 - 練習用
podman pod把一個前端容器與一個後端容器放進同一個 pod,並用localhost互相連線 - 幫自己的容器加上
--health-cmd,並觀察podman ps的健康狀態變化
接下來可以往哪裡學?
熟悉 Podman 之後,可以朝這幾個方向繼續探索:
- Docker 基礎入門:兩者指令高度相容,了解 Docker 生態(如 Docker Hub、Docker Compose)能讓你接觸更多現成資源
- SELinux 基礎入門:理解
:Z/:z掛載參數背後的原理,排查容器權限問題會更得心應手 - 網路基礎:深入理解容器網路、連接埠轉發、防火牆設定
- Kubernetes:當服務規模變大、需要跨多台主機管理容器時,是業界最主流的解決方案
容器技術是現代部署應用程式的標準做法,打好 Podman 的基礎,未來學習其他容器工具都會更加輕鬆。