podman实践常用podman命令
podman使用场景分类的常用命令:
1. 基础操作 (Basic Operations)
- 查看版本信息:
podman version
- 查看系统信息(路径、存储驱动等):
podman info
- 获取命令帮助:
podman --help
podman [command] --help
2. 镜像管理 (Image Management)
镜像就像是容器的“模板”。
- 拉取镜像:
podman pull <image_name>
- 列出本地镜像:
podman images
- 删除镜像:
podman rmi <image_id>
- 构建镜像(通过 Containerfile 或 Dockerfile):
podman build -t <tag_name> .
- 搜索镜像:
podman search <keyword>
3. 容器生命周期管理 (Container Management)
- 运行容器:
podman run -d --name <container_name> -p <host_port>:<container_port> <image_name>
-d: 后台运行
-it: 交互式运行
--rm: 容器停止后自动删除
- 列出容器(正在运行):
podman ps
- 所有容器(含停止):
podman ps -a
- 停止/启动/重启:
podman stop <container_id或者name>
podman start <container_id或者name>
podman restart <container_id或者name>
- 进入运行中的容器:
podman exec -it <container_id或者name> /bin/bash
- 查看日志:
podman logs -f <container_id>
- 删除容器:
podman rm -f <container_id>
4. Pod 管理 (Pod Management)
这是 Podman 的特色功能(源自 Kubernetes 概念),允许将多个容器组合在一起共享网络。
- 创建 Pod:
podman pod create --name <pod_name> -p 8080:80
- 在 Pod 中运行容器:
podman run -d --pod <pod_name> --name <c1> <image>
- 列出 Pod:
podman pod ps
- 停止/删除 Pod: *
podman pod stop <pod_name>
podman pod rm <pod_name>
5. 资源清理 (Cleanup)
长期使用后,系统可能会积累很多无用数据。
- 清理已停止的容器:
podman container prune
- 清理未使用的镜像:
podman image prune
- 一键全清理(谨慎使用):
podman system prune -a
6. 与 Docker 的“小抄”
如果你是从 Docker 迁移过来的,可以记住这个“必杀技”:
别名设置: 在 .bashrc 或
.zshrc 中添加
alias docker=podman
由于两者 CLI 兼容性极高,大部分脚本可以直接运行。
7.容器自启动管理 (Systemd 整合)
由于 Podman 没有守护进程,物理机重启后容器不会自动启动。Podman 的官方方案是将其生成为 Systemd 服务。 - cd用户目录:
mkdir -p ~/.config/systemd/user/
cd ~/.config/systemd/user/
- 生成 Systemd 配置文件
podman generate systemd --name <container_name> --files --new
--new参数非常重要:它确保服务启动时会自动创建容器,停止时销毁容器,保证环境洁净。
- 重载配置:
systemctl --user daemon-reload
- 设置开机自启:
systemctl --user enable --now container-<name>.service
- 让用户离线也保持运行
对于非 Root 用户,默认在注销登录后容器会停止。需要开启 linger:
loginctl enable-linger <your_username>
- 取消开机自启动
systemctl --user disable container-<name>.service
8.Systemd 常用命令
- 基础服务管理 (Service Control)
启动服务:systemctl --user start <service_name>
停止服务:systemctl --user stop <service_name>
重启服务:systemctl --user restart <service_name>
查看服务状态:systemctl --user status <service_name>
查看运行日志:journalctl --user -u <service_name> -f
> -f: 实时滚动查看
> -n 50: 查看最后 50 行
- 自启动设置 (Enable/Disable)
启用开机自启:systemctl --user enable <service_name>
取消开机自启:systemctl --user disable <service_name>
启用并立即启动:systemctl --user enable --now <service_name>
检查是否已启用:systemctl --user is-enabled <service_name>
- 配置重载与管理
重载 Systemd 配置:systemctl --user daemon-reload
列出所有活动服务:systemctl --user list-units --type=service
列出所有已安装服务(包括未运行):systemctl --user list-unit-files