强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Podman 完全指南 / 03 - 基础操作

第 03 章 — 基础操作

3.1 镜像管理

3.1.1 搜索镜像

# 从 Docker Hub 搜索
podman search nginx

# 限制返回结果数
podman search --limit 5 nginx

# 在指定仓库搜索
podman search --registry registry.access.redhat.com ubi

# 搜索结果包含 stars 和 description
podman search --format "table {{.Name}}\t{{.Stars}}\t{{.Description}}" python

3.1.2 拉取镜像

# 从 Docker Hub 拉取(默认仓库前缀 docker.io/library/)
podman pull alpine
podman pull ubuntu:24.04
podman pull nginx:1.27-alpine

# 明确指定完整路径
podman pull docker.io/library/alpine:3.20

# 从其他仓库拉取
podman pull quay.io/fedora/fedora:41
podman pull ghcr.io/owner/image:tag

# 拉取多架构镜像(指定平台)
podman pull --platform linux/arm64 alpine
podman pull --platform linux/amd64,linux/arm64 alpine

# 拉取所有标签
podman pull --all-tags docker.io/library/nginx

💡 提示

如果不指定标签,默认使用 latest。生产环境中始终指定明确的版本标签,避免 latest 带来的不确定性。

3.1.3 查看镜像

# 列出本地镜像
podman images

# 格式化输出
podman images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.Created}}"

# 只显示镜像 ID
podman images -q

# 过滤镜像
podman images --filter "dangling=true"    # 悬空镜像
podman images --filter "reference=*alpine" # 名称包含 alpine
podman images --filter "before=nginx:1.27" # 在某镜像之前创建的

# 查看镜像详细信息
podman inspect nginx:1.27-alpine

# 查看镜像分层
podman history nginx:1.27-alpine

# 查看镜像的 OCI manifest
podman manifest inspect nginx:1.27-alpine

3.1.4 镜像标签与重命名

# 给镜像打标签
podman tag nginx:1.27-alpine myregistry.io/myapp/nginx:v1.0

# 标签不会复制数据,只是创建别名
podman images
# REPOSITORY                      TAG         IMAGE ID
# docker.io/library/nginx         1.27-alpine a1b2c3d4
# myregistry.io/myapp/nginx       v1.0        a1b2c3d4  # ← 同一个 IMAGE ID

3.1.5 删除与清理镜像

# 删除指定镜像
podman rmi nginx:1.27-alpine

# 强制删除(即使有容器引用)
podman rmi -f nginx:1.27-alpine

# 删除悬空镜像(无标签的中间层)
podman image prune

# 清理所有未被使用的镜像
podman image prune -a

# 清理所有未使用的资源(镜像+容器+网络+卷)
podman system prune -a

# 查看镜像占用的磁盘空间
podman system df

3.2 容器生命周期管理

3.2.1 创建并运行容器

# 最基本的运行
podman run alpine echo "Hello World"

# 交互式运行(-it = -i -t)
podman run -it alpine /bin/sh

# 后台运行(-d = detached)
podman run -d --name webserver nginx:1.27-alpine

# 端口映射
podman run -d -p 8080:80 --name webserver nginx:1.27-alpine

# 环境变量
podman run -d -e POSTGRES_PASSWORD=secret --name db postgres:16

# 挂载卷
podman run -d -v /host/data:/container/data:Z --name app myapp

# 限制资源
podman run -d --memory 512m --cpus 1.5 --name app myapp

# 设置重启策略
podman run -d --restart=always --name webserver nginx:1.27-alpine

# 完整的企业级示例
podman run -d \
    --name production-web \
    --hostname web01 \
    -p 443:8443 \
    -e APP_ENV=production \
    -e DB_HOST=192.168.1.100 \
    -v /opt/webapp/data:/data:Z \
    -v /opt/webapp/config:/config:ro,Z \
    --memory 1g \
    --cpus 2 \
    --restart unless-stopped \
    --label app=webapp \
    --label env=production \
    registry.example.com/webapp:v2.1.0

3.2.2 容器 run 常用参数速查

参数说明示例
-d后台运行-d
-it交互式终端-it
--name容器名称--name myapp
-p端口映射-p 8080:80
-e环境变量-e KEY=value
-v挂载卷-v /host:/container:Z
--network指定网络--network mynet
--memory内存限制--memory 512m
--cpusCPU 限制--cpus 2
--restart重启策略--restart unless-stopped
--rm停止后自动删除--rm
--read-only只读根文件系统--read-only
--label添加标签--label env=prod
--add-host添加 hosts 映射--add-host db:10.0.0.5
--user指定运行用户--user 1000:1000
--workdir工作目录--workdir /app
--entrypoint覆盖入口点--entrypoint /bin/sh
--privileged特权模式--privileged(慎用)

3.2.3 查看容器

# 查看运行中的容器
podman ps

# 查看所有容器(包括已停止的)
podman ps -a

# 格式化输出
podman ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"

# 只显示容器 ID
podman ps -q

# 过滤容器
podman ps --filter "status=running"
podman ps --filter "name=web"
podman ps --filter "label=env=production"

# 查看容器资源使用情况
podman stats

# 持续监控(类似 top)
podman stats --no-stream

# 查看容器详细信息
podman inspect webserver

# 查看容器日志
podman logs webserver
podman logs -f webserver        # 持续输出
podman logs --tail 100 webserver # 最后 100 行
podman logs --since 1h webserver # 最近 1 小时

3.2.4 容器生命周期操作

# 停止容器
podman stop webserver
podman stop webserver app db    # 批量停止

# 启动已停止的容器
podman start webserver

# 重启容器
podman restart webserver

# 暂停/恢复容器
podman pause webserver
podman unpause webserver

# 删除容器
podman rm webserver
podman rm -f webserver          # 强制删除运行中的容器

# 批量清理已停止的容器
podman container prune

# 在运行中的容器中执行命令
podman exec -it webserver /bin/sh
podman exec webserver cat /etc/nginx/nginx.conf
podman exec webserver nginx -t

# 以特定用户执行
podman exec -it --user nobody webserver /bin/sh

# 查看容器进程
podman top webserver

# 查看容器的文件变更
podman diff webserver

# 复制文件(容器 ↔ 宿主机)
podman cp webserver:/etc/nginx/nginx.conf ./nginx.conf
podman cp ./config.yaml webserver:/app/config.yaml

# 等待容器退出(脚本中使用)
podman wait webserver

# 重命名容器
podman rename webserver nginx-prod

# 检查容器健康状态
podman healthcheck run webserver

3.2.5 容器生命周期状态图

                    podman create
                         │
                         ▼
┌─────────┐      ┌───────────┐
│ Created │ ───▶ │  Running  │ ◀─── podman start
└─────────┘      └─────┬─────┘
                        │
         ┌──────────────┼──────────────┐
         ▼              ▼              ▼
   podman pause   podman stop    podman kill
         │              │              │
         ▼              ▼              ▼
   ┌─────────┐   ┌───────────┐  ┌──────────┐
   │ Paused  │   │  Stopped  │  │  Killed  │
   └─────────┘   └───────────┘  └──────────┘
                        │              │
                        ▼              ▼
                  ┌──────────────────────┐
                  │      Removed         │
                  │  (podman rm)         │
                  └──────────────────────┘

3.3 构建镜像

3.3.1 编写 Dockerfile

# 多阶段构建示例 — Go 应用
# 阶段 1:构建
FROM docker.io/library/golang:1.23-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server

# 阶段 2:运行
FROM docker.io/library/alpine:3.20
RUN apk --no-cache add ca-certificates tzdata
COPY --from=builder /app /usr/local/bin/app
EXPOSE 8080
USER nobody:nobody
ENTRYPOINT ["/usr/local/bin/app"]

3.3.2 构建命令

# 基本构建
podman build -t myapp:v1.0 .

# 指定 Dockerfile 路径
podman build -t myapp:v1.0 -f Dockerfile.prod .

# 传递构建参数
podman build -t myapp:v1.0 --build-arg VERSION=2.1.0 .

# 不使用缓存
podman build -t myapp:v1.0 --no-cache .

# 指定目标阶段(多阶段构建)
podman build -t myapp:builder --target builder .

# 多架构构建
podman build --platform linux/amd64,linux/arm64 -t myapp:v1.0 .

# 使用 Buildah 构建(等效命令)
buildah bud -t myapp:v1.0 .

💡 提示

Podman 的构建功能实际上是调用 Buildah。如果你需要更复杂的构建流程,可以单独使用 Buildah 脚本化构建。


3.4 推送镜像

# 先登录仓库
podman login registry.example.com
podman login ghcr.io
podman login quay.io

# 使用 token 登录(适合 CI/CD)
echo "$REGISTRY_TOKEN" | podman login registry.example.com -u username --password-stdin

# 给镜像打远程标签
podman tag myapp:v1.0 registry.example.com/myapp:v1.0

# 推送
podman push registry.example.com/myapp:v1.0

# 推送所有标签
podman push registry.example.com/myapp --all-tags

# 推送到 Docker Hub
podman tag myapp:v1.0 docker.io/myusername/myapp:v1.0
podman push docker.io/myusername/myapp:v1.0

# 登出
podman logout registry.example.com

3.5 实战场景

场景一:快速搭建 Nginx 静态网站

# 创建网站目录
mkdir -p ~/mywebsite

# 创建一个简单页面
cat > ~/mywebsite/index.html << 'EOF'
<!DOCTYPE html>
<html>
<head><title>Podman 网站</title></head>
<body><h1>Hello from Podman!</h1></body>
</html>
EOF

# 运行 Nginx
podman run -d \
    --name mywebsite \
    -p 8080:80 \
    -v ~/mywebsite:/usr/share/nginx/html:ro,Z \
    nginx:1.27-alpine

# 访问测试
curl http://localhost:8080

场景二:临时调试容器

# 运行一个带网络工具的临时容器,退出后自动删除
podman run --rm -it nicolaka/netshoot

# 在临时容器中测试网络
ping google.com
curl -v https://example.com
nslookup kubernetes.default.svc

场景三:批量处理文件

# 使用 Python 容器处理 CSV 文件
mkdir -p ~/data

podman run --rm \
    -v ~/data:/data:Z \
    python:3.12-slim \
    python3 -c "
import csv
with open('/data/input.csv') as f:
    reader = csv.DictReader(f)
    total = sum(float(row['amount']) for row in reader)
    print(f'Total: {total}')
"

3.6 命令速查表

镜像操作

操作命令
搜索podman search <keyword>
拉取podman pull <image>:<tag>
列出podman images
标签podman tag <src> <dst>
推送podman push <image>
删除podman rmi <image>
构建podman build -t <name> .
导入podman load -i image.tar
导出podman save -o image.tar <image>
信息podman inspect <image>
历史podman history <image>
清理podman image prune

容器操作

操作命令
运行podman run [opts] <image>
列出podman ps -a
停止podman stop <container>
启动podman start <container>
重启podman restart <container>
删除podman rm <container>
执行podman exec -it <container> <cmd>
日志podman logs <container>
进程podman top <container>
变更podman diff <container>
复制podman cp <src> <dst>
信息podman inspect <container>
统计podman stats
清理podman container prune

3.7 本章小结

知识点要点
镜像管理pull / images / tag / rmi / push / build
容器生命周期create → start → running → stop → rm
交互容器-it 用于交互式,-d 用于后台运行
端口映射-p 宿主机端口:容器端口
卷挂载-v 宿主机路径:容器路径:Z(SELinux 标签)
资源限制--memory--cpus
构建镜像podman build -t name .
临时容器--rm 退出后自动清理

下一步


扩展阅读