名称
podman-quadlet-basic-usage:Podman Quadlet 基本用法示例与分步指南。
说明
本指南介绍 Podman Quadlet 的常见用法,通过分步示例说明如何使用声明式 .container、.volume 及相关单元文件定义容器、开放端口、创建卷并建立依赖关系。
Quadlet 会把这些文件转换为 systemd 服务,从而简化容器生命周期管理,并允许使用 systemctl 管理容器。
示例一:运行简单容器
步骤 1:创建 hello.container
[Unit]
Description=Hello Alpine Container
[Container]
Image=alpine
Exec=echo Hello from Quadlet!
[Install]
WantedBy=multi-user.target
步骤 2:放置文件
以非 root 身份运行时:
mkdir -p ~/.config/containers/systemd
cp hello.container ~/.config/containers/systemd/
以 root 身份运行时:
sudo cp hello.container /etc/containers/systemd/
步骤 3:重新加载并启动服务
以非 root 身份运行时:
systemctl --user daemon-reload
systemctl --user start hello.service
以 root 身份运行时:
sudo systemctl daemon-reload
sudo systemctl start hello.service
请注意,Quadlet 服务是动态生成的 systemd 单元,因此不能直接执行 enable。更多信息见 podman-systemd.unit(5)。
预期输出
非 root 模式下,使用以下命令查看日志:
journalctl --user -u hello.service
root 模式下:
journalctl -u hello.service
应当看到以下内容:Hello from Quadlet!
这表示容器已经启动、执行 echo 命令,然后退出。
示例二:创建命名卷
步骤 1:创建 mydata.volume
[Volume]
VolumeName=mydata
Label=purpose=demo
步骤 2:放置文件并重新加载
以非 root 身份运行时:
mkdir -p ~/.config/containers/systemd
cp mydata.volume ~/.config/containers/systemd/
systemctl --user daemon-reload
以 root 身份运行时:
sudo cp mydata.volume /etc/containers/systemd/
sudo systemctl daemon-reload
步骤 3:创建卷
以非 root 身份运行时:
systemctl --user start mydata-volume.service
以 root 身份运行时:
systemctl start mydata-volume.service
示例三:让容器使用卷
创建 with-volume.container
[Unit]
Description=Container with Mounted Volume
[Container]
Image=alpine
Exec=sh -c "ls /data && echo Hello > /data/hello.txt"
Volume=mydata.volume:/data
[Install]
WantedBy=multi-user.target
这个容器会列出卷中的全部文件,并创建 hello.txt。
启动容器并查看状态
以非 root 身份运行时:
cp with-volume.container ~/.config/containers/systemd/
systemctl --user daemon-reload
systemctl --user start with-volume.service
systemctl --user status with-volume.service
以 root 身份运行时:
sudo cp with-volume.container /etc/containers/systemd/
sudo systemctl daemon-reload
sudo systemctl start with-volume.service
sudo systemctl status with-volume.service
第一次启动时,systemctl status 的输出中不会出现 hello.txt,因为该文件尚未创建。第二次启动时,输出将变为:
hello.txt
这表明该卷已经被使用,而且数据能够持久保存。
示例四:将容器端口开放给主机
创建 webserver.container
[Unit]
Description=Nginx Webserver
[Container]
Image=nginx:alpine
PublishPort=8080:80
[Install]
WantedBy=multi-user.target
启动 Web 服务器
以非 root 身份运行时:
cp webserver.container ~/.config/containers/systemd/
systemctl --user daemon-reload
systemctl --user start webserver.service
以 root 身份运行时:
sudo cp webserver.container /etc/containers/systemd/
sudo systemctl daemon-reload
sudo systemctl start webserver.service
在浏览器中访问 http://localhost:8080。
使用提示
若要在系统启动时启动容器,可以使用:
[Install]
WantedBy=multi-user.target
如果 systemctl 找不到 foo.service,通常意味着 Quadlet 文件存在语法错误。可以使用以下方式查看详细信息:
systemd-analyze --user --generators=true verify foo.service
另请参阅
podman-systemd.unit(5)、podman-container.unit(5)、podman-volume.unit(5)、systemd.unit(5)
原文:Podman Quadlet: Basic Usage。作者/来源:Podman 文档贡献者。本文依据所列原文整理为中文,代码、命令与配置示例保留原文。











暂无评论内容