名称

podman-quadlet-basic-usage - Podman Quadlet 的基本用法示例和分步指南

描述

本指南介绍了 Podman Quadlet 的常见用法。它通过分步示例,演示了如何使用声明式的 .container.volume 及相关的单元文件来定义容器、暴露端口、创建卷以及建立依赖关系。

Quadlet 通过将这些文件转换为 systemd 服务,简化了容器的生命周期管理,使其可以使用 systemctl 进行管理。

示例 1:运行一个简单的容器

第 1 步:创建 hello.container

[Unit]
Description=Hello Alpine Container

[Container]
Image=alpine
Exec=echo Hello from Quadlet!

[Install]
WantedBy=multi-user.target

第 2 步:放置文件

对于无根(rootless)模式

mkdir -p ~/.config/containers/systemd
cp hello.container ~/.config/containers/systemd/

对于有根(rootful)模式

sudo cp hello.container ~/etc/containers/systemd/

第 3 步:重新加载并启用服务

对于无根(rootless)模式

systemctl --user daemon-reload
systemctl --user start hello.service

对于有根(rootful)模式

sudo systemctl daemon-reload
sudo systemctl enable --now hello.service

预期输出:

对于无根模式,使用以下命令检查日志

journalctl --user -u hello.service

对于有根模式

journalctl -u hello.service

您应该会看到:Hello from Quadlet!

这意味着容器已启动,执行了 echo 语句,然后退出了。

示例 2:创建一个命名卷

第 1 步:创建 mydata.volume

[Volume]
VolumeName=mydata
Label=purpose=demo

第 2 步:放置并重新加载

对于无根(rootless)模式

mkdir -p ~/.config/containers/systemd
cp mydata.volume ~/.config/containers/systemd/
systemctl --user daemon-reload

对于有根(rootful)模式

sudo cp mydata.volume /etc/containers/systemd/
sudo systemctl daemon-reload

第 3 步:创建卷

对于无根(rootless)模式

systemctl --user start mydata-volume.service

对于有根(rootful)模式

systemctl start mydata-volume.service

示例 3:使用卷的容器

创建 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=default.target

此容器会显示卷上的所有文件,并创建 hello.txt 文件。

启动容器并检查状态

对于无根(rootless)模式

cp with-volume.container ~/.config/containers/systemd/
systemctl --user daemon-reload
systemctl --user start with-volume.service
systemctl --user status with-volume.service

对于有根(rootful)模式

sudo cp with-volume.container /etc/containers/systemd/
sudo systemctl daemon-reload
sudo systemctl start with-volume.service
sudo systemctl status with-volume.service

首次启动时,hello.txt 不会出现在 systemctl status 的输出中,因为它尚未被创建。但当第二次启动时,输出将是

hello.txt

这表示该卷正在被使用并且是持久的。

示例 4:将容器端口暴露到主机

创建 webserver.container

[Unit]
Description=Nginx Webserver

[Container]
Image=nginx:alpine
PublishPort=8080:80

[Install]
WantedBy=default.target

启动 Web 服务器

对于无根(rootless)模式

cp webserver.container ~/.config/containers/systemd/
systemctl --user daemon-reload
systemctl --user start webserver.service

对于有根(rootful)模式

sudo cp webserver.container ~/.config/containers/systemd/
sudo systemctl daemon-reload
sudo systemctl start webserver.service

在浏览器中访问 https://:8080

提示

要在系统启动时启动容器,请使用

[Install]
WantedBy=multi-user.target default.target

如果 foo.service 文件没有生成,通常意味着您的 quadlet 文件中存在语法错误。要查找详细信息,请使用

systemd-analyze --user --generators=true verify foo.service

另请参阅

podman-quadlet(7)podman-container.unit(5)podman-volume.unit(5)systemd.unit(5)

作者

Podman 团队 https://podman.org.cn