Podman容器技术基础入门

导读:本篇文章讲解 Podman容器技术基础入门,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、介绍podman

1.1 为什么使用podman

podman(Pod Manager)是一个由RedHat公司推出的容器管理工具,它的定位就是docker的替代品,在使用上与docker的体验类似。 podman源于CRI-O项目,可以直接访问OCI的实现(如runC),流程比docker要短。 二者主要的区别在于,podman是一个开源的产品;而docker已经是商业化的产品。 podman的开源代码,由RedHat的OpenShift项目维护。 podman.io上面的文档还不算很健全,作为普通开发者,将其当成docker去用,难度也不算很大。

Podman 是 Docker 的替代品,用于容器化应用程序的本地开发。Podman 命令将 1 对 1 映射 Docker 命令,包括它们的参数。你可以使用 podman 为 docker 添加别名,并且从不会发现管理本地容器的是两种完全不同的工具。Podman 的核心功能之一是它专注于**安全性。**使用 Podman 不需要守护进程。相反,它使用传统的 fork-exec 模型,并且大量地使用 用户名称空间 和 网络名称空间 。因此,Podman 比 Docker 更加孤立,使用起来也更安全。更多细节请点击这里podman官网地址

podman项目地址

1.2 podman与docker的区别

在这里插入图片描述

  • docker 需要在我们的系统上运行一个守护进程(docker daemon),而podman 不需要

  • 启动容器的方式不同: docker cli 命令通过API跟 Docker Engine(引擎)交互告诉它我想创建一个container,然后docker engine才会调用 OCI container

  • runtime(runc)来启动一个container。这代表container的process(进程)不会是Docker CLI的child process(子进程),而是 Docker Engine 的child process。 Podman是直接给OCI,containner runtime(runc)进行交互来创建container的,所以container的process直接是podman的child process。

  • 因为docke有docker daemon,所以docker启动的容器支持–restart策略,但是podman不支持,如果在k8s中就不存在这个问题,我们可以设置pod的重启策略,在系统中我们可以采用编写systemd服务来完成自启动docker需要使用root用户来创建容器,但是podman不需要

在这里插入图片描述

注意:podman相比docker也缺失了一些功能,比如不支持windows,不支持docker-compoese编排工具。显然在Kubernetes或者OpenShift体系中,这些并不重要

1.3 podman的工作机制

Podman 原来是 CRI-O 项目的一部分,后来被分离成一个单独的项目叫 libpod。Podman 的使用体验和 Docker类似,不同的是 Podman 没有 daemon。以前使用 Docker CLI 的时候,Docker CLI 会通过 gRPC API
去跟 Docker Engine 说「我要启动一个容器」,然后 Docker Engine 才会通过 OCI Container。

runtime(默认是 runc)来启动一个容器。这就意味着容器的进程不可能是 Docker CLI 的子进程,而是 Docker
Engine 的子进程。

Podman 比较简单粗暴,它不使用 Daemon,而是直接通过 OCI runtime(默认也是 runc)来启动容器,所以容器的进程是 podman 的子进程。这比较像 Linux 的 fork/exec 模型,而 Docker 采用的是 C/S(客户端/服务器)模型。与 C/S 模型相比,fork/exec 模型有很多优势,比如:

  • 系统管理员可以知道某个容器进程到底是谁启动的。
  • 如果利用 cgroup 对 podman 做一些限制,那么所有创建的容器都会被限制。
  • SD_NOTIFY : 如果将 podman 命令放入 systemd 单元文件中,容器进程可以通过 podman 返回通知,表明服务已准备好接收任务。
  • socket 激活 : 可以将连接的 socket 从 systemd 传递到 podman,并传递到容器进程以便使用它们。

二、安装podman

[root@localhost ~]# yum -y install podman

[root@localhost ~]# rpm -qa | grep podman
podman-3.4.1-3.module_el8.6.0+954+963caf36.x86_64
podman-catatonit-3.4.1-3.module_el8.6.0+954+963caf36.x86_64

// 定义别名
[root@localhost ~]# alias docker=podman
[root@localhost ~]# docker images
REPOSITORY  TAG         IMAGE ID    CREATED     SIZE

[root@localhost ~]# podman images
REPOSITORY  TAG         IMAGE ID    CREATED     SIZE

三、podman使用帮助

要获得一些帮助并了解Podman的工作原理,您可以使用以下帮助:

$ podman --help
$ podman <subcommand> --help
$ podman --version 	// 查看podman版本

有关更多详细信息,您可以查看手册页:

$ man podman
$ man podman-<subcommand>

另请参阅Podman 故障排除指南,以查找有关如何解决常见配置错误的已知问题和提示。

四、podman常用基础命令

4.1 podman search:查找

// --filter=is-official:指定查找官方版本的httpd
[root@localhost ~]# podman search httpd --filter=is-official
INDEX       NAME                     DESCRIPTION                     STARS       OFFICIAL    AUTOMATED
docker.io   docker.io/library/httpd  The Apache HTTP Server Project  3794        [OK]     

4.2 podman pull:下载(拉取)镜像

注意:Podman在不同的注册管理机构中搜索。因此,建议使用完整的映像名称(docker.io/library/httpd而不是httpd)来确保使用正确的映像

// 拉取httpd镜像
[root@localhost ~]# podman pull docker.io/library/httpd
Trying to pull docker.io/library/httpd:latest...
Getting image source signatures
Copying blob aa379c0cedc2 done  
Copying blob bc36ee1127ec done  
Copying blob f1aa5f54b226 done  
Copying blob d3576f2b6317 done  
Copying blob e5ae68f74026 done  
Copying config ea28e1b82f done  
Writing manifest to image destination
Storing signatures
ea28e1b82f314092abd3f90a69e57d6ccf506382821ee0b8d9b48c3e47440c1f

// 当你不知道镜像准确位置,无法确定的时候,直接podman pull + 镜像名,然后上下滑动选择你要指定拉取镜像的位置
[root@localhost ~]# podman pull nginx
? Please select an image: 
    registry.fedoraproject.org/nginx:latest
    registry.access.redhat.com/nginx:latest
    registry.centos.org/nginx:latest
  ▸ docker.io/library/nginx:latest

4.3 podman images:显示所有镜像

[root@localhost ~]# podman images
REPOSITORY               TAG         IMAGE ID      CREATED        SIZE
docker.io/library/httpd  latest      ea28e1b82f31  11 days ago    148 MB
quay.io/centos/centos    latest      300e315adb2f  12 months ago  217 MB

4.4 podman run:运行容器

运行一个非常基本的 httpd 服务器

[root@localhost ~]# podman run -d -p 80:80 docker.io/library/httpd
485105d6adb8b2e12283111fb6c2f3a039ff79d786695958ae9dacd1fa4415e6

注意:由于容器在分离模式下运行,由命令中的 表示,Podman将在执行命令后打印容器ID。它还添加了一个伪 tty,用于在交互式 shell 中运行任意命令。-d``podman run``-t

注意:我们使用端口转发来访问HTTP服务器。要成功运行,至少需要 slirp4netns v0.3.0。

4.5 podman ps:列出正在运行的容器

// 查看刚刚运行的httpd
[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                           COMMAND           CREATED        STATUS            PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  4 seconds ago  Up 3 seconds ago  0.0.0.0:80->80/tcp  vigorous_turing

页面访问

在这里插入图片描述

注意:如果添加 -a 命令,Podman 将显示所有容器(已创建、已退出、正在运行等)

[root@localhost ~]# podman ps -a
CONTAINER ID  IMAGE                           COMMAND           CREATED        STATUS            PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  5 minutes ago  Up 5 minutes ago  0.0.0.0:80->80/tcp  vigorous_turing

4.6 podman inspect:查看容器详细信息

  • -l:查看最新信息(最新的信息以最新的时间来定义)

您可以”检查”正在运行的容器,以查找有关其自身的元数据和详细信息。 将提供许多有用的信息,如环境变量,网络设置或分配的资源。podman inspect

由于容器在无根模式下运行,因此不会为容器分配 IP 地址。

[root@localhost ~]# podman ps -a
CONTAINER ID  IMAGE                           COMMAND           CREATED        STATUS            PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  5 minutes ago  Up 5 minutes ago  0.0.0.0:80->80/tcp  vigorous_turing
[root@localhost ~]# podman inspect 485105d6adb8
[
    {
        "Id": "485105d6adb8b2e12283111fb6c2f3a039ff79d786695958ae9dacd1fa4415e6",
        "Created": "2021-12-14T10:19:25.522855463+08:00",
        "Path": "httpd-foreground",
        "Args": [
            "httpd-foreground"
        ],
        "State": {
            "OciVersion": "1.0.2-dev",
            "Status": "running",
......后面省略

// -l 查看最新信息
[root@localhost ~]# podman inspect -l | grep IPAddress
            "IPAddress": "10.88.0.2",
                    "IPAddress": "10.88.0.2",

4.7 curl + IP:访问测试页面

如您所见,容器未分配 IP 地址。容器可通过本地计算机上的已发布端口访问。

[root@localhost ~]# curl 192.168.91.137
<html><body><h1>It works!</h1></body></html>

在另一台计算机上,需要使用运行容器的主机的 IP 地址。

$ curl http://<IP_Address>:80

注意:除了使用curl之外,您还可以将浏览器指向http://localhost:80。

4.8 podman logs:查看容器日志

  • -l:查看最新日志
[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                           COMMAND           CREATED         STATUS             PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  21 minutes ago  Up 21 minutes ago  0.0.0.0:80->80/tcp  vigorous_turing

// 查看指定容器日志
[root@localhost ~]# podman logs 485105d6adb8
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 10.88.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 10.88.0.2. Set the 'ServerName' directive globally to suppress this message
[Tue Dec 14 02:19:26.304224 2021] [mpm_event:notice] [pid 1:tid 140380177263936] AH00489: Apache/2.4.51 (Unix) configured -- resuming normal operations
[Tue Dec 14 02:19:26.304364 2021] [core:notice] [pid 1:tid 140380177263936] AH00094: Command line: 'httpd -D FOREGROUND'
192.168.91.1 - - [14/Dec/2021:02:19:49 +0000] "GET / HTTP/1.1" 200 45
192.168.91.1 - - [14/Dec/2021:02:19:49 +0000] "GET /favicon.ico HTTP/1.1" 404 196
192.168.91.1 - - [14/Dec/2021:02:35:29 +0000] "GET / HTTP/1.1" 304 -
192.168.91.1 - - [14/Dec/2021:02:35:31 +0000] "GET / HTTP/1.1" 304 -
192.168.91.137 - - [14/Dec/2021:02:36:18 +0000] "GET / HTTP/1.1" 200 45
192.168.91.1 - - [14/Dec/2021:02:36:21 +0000] "-" 408 -

[root@localhost ~]# podman logs -l
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 10.88.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 10.88.0.2. Set the 'ServerName' directive globally to suppress this message
[Tue Dec 14 02:19:26.304224 2021] [mpm_event:notice] [pid 1:tid 140380177263936] AH00489: Apache/2.4.51 (Unix) configured -- resuming normal operations
[Tue Dec 14 02:19:26.304364 2021] [core:notice] [pid 1:tid 140380177263936] AH00094: Command line: 'httpd -D FOREGROUND'
192.168.91.1 - - [14/Dec/2021:02:19:49 +0000] "GET / HTTP/1.1" 200 45
192.168.91.1 - - [14/Dec/2021:02:19:49 +0000] "GET /favicon.ico HTTP/1.1" 404 196
192.168.91.1 - - [14/Dec/2021:02:35:29 +0000] "GET / HTTP/1.1" 304 -
192.168.91.1 - - [14/Dec/2021:02:35:31 +0000] "GET / HTTP/1.1" 304 -
192.168.91.137 - - [14/Dec/2021:02:36:18 +0000] "GET / HTTP/1.1" 200 45
192.168.91.1 - - [14/Dec/2021:02:36:21 +0000] "-" 408 -

4.9 podman top:查看容器的 pids

  • -l:查看最新的
// 查看httpd容器的pids
[root@localhost ~]# podman top 485105d6adb8
USER        PID         PPID        %CPU        ELAPSED           TTY         TIME        COMMAND
root        1           0           0.000       23m32.109319421s  ?           0s          httpd -DFOREGROUND 
www-data    8           1           0.000       23m31.109395119s  ?           0s          httpd -DFOREGROUND 
www-data    9           1           0.000       23m31.109433423s  ?           0s          httpd -DFOREGROUND 
www-data    11          1           0.000       23m31.10947179s   ?           0s          httpd -DFOREGROUND 
www-data    92          1           0.000       6m55.109510152s   ?           0s          httpd -DFOREGROUND 


// 查看最新的pids
[root@localhost ~]# podman top -l
USER        PID         PPID        %CPU        ELAPSED           TTY         TIME        COMMAND
root        1           0           0.000       22m56.673908965s  ?           0s          httpd -DFOREGROUND 
www-data    8           1           0.000       22m55.674052375s  ?           0s          httpd -DFOREGROUND 
www-data    9           1           0.000       22m55.674097414s  ?           0s          httpd -DFOREGROUND 
www-data    11          1           0.000       22m55.674134502s  ?           0s          httpd -DFOREGROUND 
www-data    92          1           0.000       6m19.674173218s   ?           0s          httpd -DFOREGROUND 

4.10 podman stop:停止容器

  • -l:停止最新的容器
[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                           COMMAND           CREATED         STATUS             PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  24 minutes ago  Up 24 minutes ago  0.0.0.0:80->80/tcp  vigorous_turing

[root@localhost ~]# podman stop -l
485105d6adb8b2e12283111fb6c2f3a039ff79d786695958ae9dacd1fa4415e6

[root@localhost ~]# podman ps
CONTAINER ID  IMAGE       COMMAND     CREATED     STATUS      PORTS       NAMES

4.11 podman start:启动容器

  • -l:启动最新的容器
[root@localhost ~]# podman start -l
485105d6adb8b2e12283111fb6c2f3a039ff79d786695958ae9dacd1fa4415e6

[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                           COMMAND           CREATED         STATUS            PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  34 minutes ago  Up 2 seconds ago  0.0.0.0:80->80/tcp  vigorous_turing

4.12 podman rm:删除容器

  • -f:强制删除
  • -l:指定最新的
[root@localhost ~]# podman ps -a
CONTAINER ID  IMAGE                           COMMAND           CREATED         STATUS                     PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  11 minutes ago  Up 11 minutes ago          0.0.0.0:80->80/tcp  vigorous_turing
7b8ff83d4e9d  quay.io/centos/centos:latest    /bin/bash         12 seconds ago  Exited (0) 12 seconds ago                      elegant_elion

// -f强制删除、-l删除最新的
[root@localhost ~]# podman rm -f -l
7b8ff83d4e9da57284edb7708b1d0c23d413ab872b07c4810df46ab15d29691c
[root@localhost ~]# podman ps -a
CONTAINER ID  IMAGE                           COMMAND           CREATED         STATUS             PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  11 minutes ago  Up 11 minutes ago  0.0.0.0:80->80/tcp  vigorous_turing

[root@localhost ~]# podman ps -a
CONTAINER ID  IMAGE                           COMMAND           CREATED         STATUS             PORTS               NAMES
485105d6adb8  docker.io/library/httpd:latest  httpd-foreground  13 minutes ago  Up 13 minutes ago  0.0.0.0:80->80/tcp  vigorous_turing

4.13 podman rmi:删除镜像

  • -f:强制删除
[root@localhost ~]# podman images
REPOSITORY               TAG         IMAGE ID      CREATED        SIZE
docker.io/library/httpd  latest      ea28e1b82f31  11 days ago    148 MB
quay.io/centos/centos    latest      300e315adb2f  12 months ago  217 MB

[root@localhost ~]# podman rmi -f 300e315adb2f
Untagged: quay.io/centos/centos:latest
Deleted: 300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55

[root@localhost ~]# podman images
REPOSITORY               TAG         IMAGE ID      CREATED      SIZE
docker.io/library/httpd  latest      ea28e1b82f31  11 days ago  148 MB

4.14 podman tag:修改标签(改名)

[root@localhost ~]# podman images
REPOSITORY                 TAG         IMAGE ID      CREATED       SIZE
docker.io/library/busybox  latest      ffe9d497c324  6 days ago    1.46 MB
docker.io/library/nginx    latest      f652ca386ed1  11 days ago   146 MB
docker.io/library/httpd    latest      ea28e1b82f31  11 days ago   148 MB
docker.io/library/centos   latest      5d0da3dc9764  2 months ago  239 MB

[root@localhost ~]# podman tag docker.io/library/nginx:latest docker.io/gaofan1225/nginx:v0.1

[root@localhost ~]# podman images
REPOSITORY                   TAG         IMAGE ID      CREATED       SIZE
docker.io/library/busybox    latest      ffe9d497c324  6 days ago    1.46 MB
docker.io/library/nginx      latest      f652ca386ed1  11 days ago   146 MB
docker.io/gaofan1225/nginx  v0.1        f652ca386ed1  11 days ago   146 MB
docker.io/library/httpd      latest      ea28e1b82f31  11 days ago   148 MB
docker.io/library/centos     latest      5d0da3dc9764  2 months ago  239 MB

4.15 podman push:上传镜像

// 登录仓库,podman需要制定登录仓库
[root@localhost ~]# podman login docker.io 
Username: gaofan1225
Password: 
Login Succeeded!

[root@localhost ~]# cat /run/user/0/containers/auth.json
{
        "auths": {
                "docker.io": {
                        "auth": "Z2FvZmFuMTIyNToxOTk5MTIyNWdm"
                }
        }

// 开始上传
[root@localhost ~]# podman push docker.io/gaofan1225/nginx:0.1

4.16 podman info:显示整个系统信息

[root@localhost ~]# podman info
host:
  arch: amd64
  buildahVersion: 1.23.1
  cgroupControllers:
  - cpuset
  - cpu
  - cpuacct
  - blkio
  - memory
  - devices
  - freezer
  - net_cls
  - perf_event
  - net_prio
  - hugetlb
  - pids
  - rdma
  cgroupManager: systemd
  cgroupVersion: v1

五、普通用户使用的配置

在允许没有root特权的用户运行Podman之前,管理员必须安装或构建Podman并完成以下配置
cgroup V2 Linux 内核功能允许用户限制无根容器可以使用的资源量。如果您运行 Podman 的 Linux 发行版已启用 cgroup V2,则可能需要更改默认的 OCI 运行时。某些较旧版本的 无法与 cgroup V2 配合使用,您可能需要切换到备用 OCI 运行时 。runc crun

5.1 crun

安装 crun

[root@podman ~]# dnf -y install crun
//修改配置文件,把 'runc' 修改为 'crun'
[root@localhost ~]# vim /usr/share/containers/containers.conf 

# Default OCI runtime
#
runtime = "crun"

// 运行一个nginx容器
[root@localhost ~]# podman run -d --name nginx -p 80:80 docker.io/library/nginx
a72d3d952c35a656c12a338ad88eb6c3e58695a01603fb7ac0067fe45647eb69

[root@localhost ~]# podman inspect nginx | grep crun
        "OCIRuntime": "crun",
            "crun",

5.2 slirp4netns

安装slirp4netns
slirp4netns包是为普通用户提供一种网络模式

[root@localhost ~]# yum -y install slirp4netns

5.3 fuse-overlayfs

安装fuse-overlayfs
在普通用户环境中使用Podman时,建议使用fuse-overlayfs而不是VFS文件系统,至少需要版本0.7.6。

[root@localhost ~]# yum -y install fuse-overlayfs

修改 storage.conf 文件

[root@localhost ~]# vim /etc/containers/storage.conf 

# Default Storage Driver
driver = "overlay"

......
mount_program = "/usr/bin/fuse-overlayfs"
//取消这行的注释

5.4 /etc/subuid和/etc/subgid配置

Podman要求运行它的用户 /etc/subuid 和 /etc/subgid 文件中列出一系列 UID,shadow-utils 或 newuid包 提供这些文件

//centos 8 自带的有这个包,再安装一次就更新了这个包
[root@localhost ~]# yum -y install shadow-utils

可以在 /etc/subuid 和 /etc/subgid 查看,每个用户的值必须唯一且没有任何重叠。

[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                           COMMAND               CREATED         STATUS             PORTS               NAMES
a72d3d952c35  docker.io/library/nginx:latest  nginx -g daemon o...  10 minutes ago  Up 10 minutes ago  0.0.0.0:80->80/tcp  nginx
[root@localhost ~]# podman exec -it nginx /bin/bash

root@a72d3d952c35:/# id
uid=0(root) gid=0(root) groups=0(root)
root@a72d3d952c35:/# cat /etc/subuid 
root@a72d3d952c35:/# useradd test
root@a72d3d952c35:/# cat /etc/subuid
test:100000:65536

5.5 用户的配置文件

三个主要的配置文件是 container.conf,storage.conf 和 registries.conf。用户可以根据需要修改这些文件。

container.conf

Podman读取时,按照循序来了,当前面一位找不到时,就去找下一个

/usr/share/containers/containers.conf

/etc/containers/containers.conf

$HOME/.config/containers/containers.conf

storage.conf

/etc/containers/storage.conf

在普通用户中 /etc/containers/storage.conf 的一些字段将被忽略

graphroot=``""`` ``container storage graph ``dir` `(default: ``"/var/lib/containers/storage"``)`` ``Default directory to store all writable content created by container storage programs.` `runroot=``""`` ``container storage run ``dir` `(default: ``"/run/containers/storage"``)`` ``Default directory to store all temporary writable content created by container storage programs.

在普通用户中这些字段默认

graphroot=``"$HOME/.local/share/containers/storage"``runroot=``"$XDG_RUNTIME_DIR/containers"

registries.conf

如果这些文件不是默认创建的,可以从/usr/share/containers或复制文件/etc/containers并进行修改。

/etc/containers/registries.conf

/etc/containers/registries.d/

HOME/.config/containers/registries.conf

5.6 授权文件

podman login 登录,默认授权文件位于中${XDG_RUNTIME_DIR}/containers/auth.json

[root@localhost ~]# find / -name auth.json
/run/user/0/containers/auth.json

[root@localhost ~]# cat /run/user/0/containers/auth.json
{
        "auths": {
                "docker.io": {
                        "auth": "Z2FvZmFuMTIyNToxOTk5MTIyNWdm"
                }
        }
}

5.7 使用卷

容器与root用户一起运行,则root容器中的用户实际上就是主机上的用户。UID / GID 1是在/etc/subuid和/etc/subgid等中用户映射中指定的第一个UID / GID 。如果普通用户的身份从主机目录挂载到容器中,并在该目录中以根用户身份创建文件,则会看到它实际上是你的用户在主机上拥有的。

// 关闭firewalld和selinux
[root@localhost ~]# systemctl stop --now firewalld
[root@localhost ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.

[root@localhost ~]# vim /etc/selinux/config 
SELINUX=disabled

// 重启一下
[root@localhost ~]# reboot

// 创建一个普通用户tom
[root@localhost ~]# useradd tom
[root@localhost ~]# su - tom
[tom@localhost ~]$ mkdir amu

// 拉取一个latest镜像
[tom@localhost ~]$ podman pull docker.io/library/busybox:latest
Resolved "busybox" as an alias (/etc/containers/registries.conf.d/000-shortnames.conf)
Trying to pull docker.io/library/busybox:latest...
Getting image source signatures
Copying blob 3cb635b06aa2 done  
Copying config ffe9d497c3 done  
Writing manifest to image destination
Storing signatures
ffe9d497c32414b1c5cdad8178a85602ee72453082da2463f1dede592ac7d5af

[tom@localhost ~]$ podman images
REPOSITORY                 TAG         IMAGE ID      CREATED     SIZE
docker.io/library/busybox  latest      ffe9d497c324  7 days ago  1.46 MB

// 运行一个test容器,测试存储卷情况
[tom@localhost ~]$ podman run -it --name test -v "$(pwd)"/amu:/amu busybox /bin/sh
/ # touch amu/haha
/ # ls -l amu/haha 
-rw-r--r--    1 root     root             0 Dec 15 02:45 amu/haha
/ # echo "hello world" > amu/haha 
/ # cat amu/haha 
hello world
/ # exit

[tom@localhost ~]$ ll
total 0
drwxrwxr-x 2 tom tom 18 Dec 15 10:45 amu

[tom@localhost ~]$ cat amu/haha 
hello world

--userns=keep-id标志,以确保用户被映射到容器内自己的UID和GID

[tom@localhost ~]$ podman run -it --name test2 -v "$(pwd)"/amu:/amu2 --userns=keep-id busybox /bin/sh
~ $ touch amu2/test
~ $ ls -l amu2/
total 4
-rw-r--r--    1 tom      tom             12 Dec 15 02:46 haha
-rw-r--r--    1 tom      tom              0 Dec 15 02:49 test
~ $ exit

[tom@localhost ~]$ ll amu/
total 4
-rw-r--r-- 1 tom tom 12 Dec 15 10:46 haha
-rw-r--r-- 1 tom tom  0 Dec 15 10:49 test
// 使用普通用户映射容器端口时会报 "permission denied" 的错误
[tom@localhost ~]$ podman run --name nginx -d -p 80:80 docker.io/library/nginx:latest
Trying to pull docker.io/library/nginx:latest...
Getting image source signatures
Copying blob ed835de16acd done  
Copying blob 881ff011f1c9 done  
Copying blob e5ae68f74026 done  
Copying blob 44be98c0fab6 done  
Copying blob 21e0df283cd6 done  
Copying blob 77700c52c969 done  
Copying config f652ca386e done  
Writing manifest to image destination
Storing signatures

// 映射80端口错误
Error: rootlessport cannot expose privileged port 80, you can add 'net.ipv4.ip_unprivileged_port_start=80' to /etc/sysctl.conf (currently 1024), or choose a larger port number (>= 1024): listen tcp 0.0.0.0:80: bind: permission denied

// nginx镜像其实已经有了
[tom@localhost ~]$ podman images
REPOSITORY                 TAG         IMAGE ID      CREATED      SIZE
docker.io/library/busybox  latest      ffe9d497c324  7 days ago   1.46 MB
docker.io/library/nginx    latest      f652ca386ed1  12 days ago  146 MB

可以映射>=1024的端口

[tom@localhost ~]$ podman run --name abc -d -p 1025:80 nginx
a18f6e33029e67fbea80fe67735724d505655b1f8d354a37df394d1711f4cf4d

[tom@localhost ~]$ ss -antl
State  Recv-Q Send-Q Local Address:Port   Peer Address:Port Process                                                     
LISTEN 0      128          0.0.0.0:22          0.0.0.0:*                                                                
LISTEN 0      128             [::]:22             [::]:*                                                                
LISTEN 0      128                *:1025              *:*    

配置 echo ‘net.ipv4.ip_unprivileged_port_start=80’ >> /etc/sysctl.conf

[root@localhost ~]# echo 'net.ipv4.ip_unprivileged_port_start=80'  >> /etc/sysctl.conf
[root@localhost ~]# sysctl -p
net.ipv4.ip_unprivileged_port_start = 80
[tom@localhost ~]$ podman run --name nginx1 -d -p 80:80 nginx
fc6261b92a77419466d1bf2e8da8d23278311b912f496b1aff633812ad74535d

[tom@localhost ~]$ ss -antl
State  Recv-Q Send-Q Local Address:Port   Peer Address:Port Process                                                     
LISTEN 0      128          0.0.0.0:22          0.0.0.0:*                                                                
LISTEN 0      128                *:80                *:*                                                                
LISTEN 0      128             [::]:22             [::]:*                                                                
LISTEN 0      128                *:1025              *:*    

[tom@localhost ~]$ podman ps
CONTAINER ID  IMAGE                           COMMAND               CREATED             STATUS                 PORTS                 NAMES
a18f6e33029e  docker.io/library/nginx:latest  nginx -g daemon o...  About a minute ago  Up About a minute ago  0.0.0.0:1025->80/tcp  abc
fc6261b92a77  docker.io/library/nginx:latest  nginx -g daemon o...  20 seconds ago      Up 20 seconds ago      0.0.0.0:80->80/tcp    nginx1

页面访问

在这里插入图片描述

六、podman网络配置

rootfull和rootless容器网络之间的差异

podman容器联网的指导因素之一将是容器是否由root用户运行。这是因为非特权用户无法在主机上创建网络接口。因此,对于rootfull容器,默认网络模式是使用容器网络接口(CNI)插件,特别是桥接插件。对于rootless,默认的网络模式是slir4netns。由于权限有限,slirnetns缺少CNI组网的一些功能;例如,slirp4netns无法为容器提供可路由的IP地址。cni是容器网络接口。

网络三部曲:

  • podman network create 创建网络
  • 修改 /etc/cni/net.d/mynetwork.conflist 配置文件
  • 修改设置 /usr/share/containers/containers.conf 将其为默认网络创建网络

创建网络

// 创建
[root@localhost ~]# podman network create network
/etc/cni/net.d/network.conflist

// 查看
[root@localhost ~]# podman network ls
NETWORK ID    NAME        VERSION     PLUGINS
2f259bab93aa  podman      0.4.0       bridge,portmap,firewall,tuning
3009be769fb8  network     0.4.0       bridge,portmap,firewall,tuning

修改 /etc/cni/net.d/mynetwork.conflist 配置文件

[root@localhost ~]# vim /etc/cni/net.d/network.conflist 
{
   "cniVersion": "0.4.0",
   "name": "network",
   "plugins": [
      {
         "type": "bridge",
         "bridge": "cni-podman1",
         "isGateway": true,
         "ipMasq": true,
         "hairpinMode": true,
         "ipam": {
            "type": "host-local",
            "routes": [
               {
                  "dst": "0.0.0.0/0"
               }
            ],
            "ranges": [
               [
                  {
                     "subnet": "192.168.92.0/24",	// 修改网段
                     "gateway": "192.168.92.1"		// 修改网关
                  }
               ]
            ]
         }
      },
      {
         "type": "portmap",
         "capabilities": {
            "portMappings": true
         }
      },
      {
         "type": "firewall",
         "backend": ""
      },
      {
         "type": "tuning"
      }
   ]
}

修改 /usr/share/containers/containers.conf 将其为默认网络

[root@localhost ~]# vim /usr/share/containers/containers.conf 
#
default_network = "network"
#default_network = "podman"

创建容器进行测试

[root@localhost ~]# podman run -it --name test busybox 
39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4

[root@localhost ~]# podman exec -it test /bin/sh
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue 
    link/ether fe:75:34:75:70:2e brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.3/24 brd 192.168.92.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::fc75:34ff:fe75:702e/64 scope link 
       valid_lft forever preferred_lft forever

// 测试能否ping通百度
/ # ping www.baidu.com
PING www.baidu.com (14.215.177.38): 56 data bytes
64 bytes from 14.215.177.38: seq=0 ttl=127 time=22.808 ms
64 bytes from 14.215.177.38: seq=1 ttl=127 time=30.320 ms
64 bytes from 14.215.177.38: seq=2 ttl=127 time=21.873 ms

七、防火墙

防火墙的作用不会影响网络的设置和配置,但会影响这些网络上的流量。最明显的是容器主机的入站网络流量,这些流量通常通过端口映射传递到容器上。根据防火墙的实现,我们观察到防火墙端口由于运行带有端口映射的容器(例如)而自动打开。如果容器流量似乎无法正常工作,请检查防火墙并允许容器正在使用的端口号上的流量。一个常见的问题是重新加载防火墙会删除cni iptables规则,从而导致rootful容器的网络连接丢失。podman v3提供了podman network reload命令来恢复它而无需重新启动容器。

基本网络设置

大多数使用 Podman 运行的容器和 Pod 都遵循几个简单的场景。默认情况下,rootfull Podman 将创建一个桥接网络。这是 Podman 最直接和首选的网络设置。桥接网络在内部桥接网络上为容器创建一个接口,然后通过网络地址转换(NAT)连接到互联网。我们还看到用户也希望macvlan 用于联网。这macvlan插件将整个网络接口从主机转发到容器中,允许它访问主机所连接的网络。最后,无根容器的默认网络配置是 slirp4netns。slirp4netns 网络模式功能有限,但可以在没有 root 权限的用户上运行。它创建了一个从主机到容器的隧道来转发流量。

查看防火墙规则

[root@localhost ~]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-4533b65d6aadf8714d7c3749  all  --  *      *       192.168.92.4         0.0.0.0/0            /* name: "network" id: "39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4" */

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-4533b65d6aadf8714d7c3749 (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.92.0/24      /* name: "network" id: "39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4" */
    0     0 MASQUERADE  all  --  *      *       0.0.0.0/0           !224.0.0.0/4          /* name: "network" id: "39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4" */

// 现在只能看见刚刚创建的网卡映射

运行一个 httpd 容器,映射 80 端口号

[root@localhost ~]# podman run -d -p 80:80 --name httpd httpd
1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171

[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                             COMMAND           CREATED        STATUS            PORTS               NAMES
39de6c87e8e7  docker.io/library/busybox:latest  sh                3 minutes ago  Up 3 minutes ago                      test
1e0fcb197f3a  docker.io/library/httpd:latest    httpd-foreground  6 seconds ago  Up 5 seconds ago  0.0.0.0:80->80/tcp  httpd

再次查看防火墙规则,发现 80 端口

[root@localhost ~]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-DNAT  all  --  *      *       0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-MASQ  all  --  *      *       0.0.0.0/0            0.0.0.0/0            /* CNI portfwd requiring masquerade */
    0     0 CNI-4533b65d6aadf8714d7c3749  all  --  *      *       192.168.92.4         0.0.0.0/0            /* name: "network" id: "39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4" */
    0     0 CNI-b823093c81076a7b3058c742  all  --  *      *       192.168.92.6         0.0.0.0/0            /* name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-DNAT  all  --  *      *       0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain CNI-4533b65d6aadf8714d7c3749 (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.92.0/24      /* name: "network" id: "39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4" */
    0     0 MASQUERADE  all  --  *      *       0.0.0.0/0           !224.0.0.0/4          /* name: "network" id: "39de6c87e8e712025ce5a9a691247950fc92918dd5a9dafa376696b0c5c8aea4" */

Chain CNI-HOSTPORT-SETMARK (2 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 MARK       all  --  *      *       0.0.0.0/0            0.0.0.0/0            /* CNI portfwd masquerade mark */ MARK or 0x2000

Chain CNI-HOSTPORT-MASQ (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 MASQUERADE  all  --  *      *       0.0.0.0/0            0.0.0.0/0            mark match 0x2000/0x2000

Chain CNI-HOSTPORT-DNAT (2 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-DN-b823093c81076a7b3058c  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            /* dnat name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */ multiport dports 80

Chain CNI-b823093c81076a7b3058c742 (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.92.0/24      /* name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */
    0     0 MASQUERADE  all  --  *      *       0.0.0.0/0           !224.0.0.0/4          /* name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */

Chain CNI-DN-b823093c81076a7b3058c (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-SETMARK  tcp  --  *      *       192.168.92.0/24      0.0.0.0/0            tcp dpt:80
    0     0 CNI-HOSTPORT-SETMARK  tcp  --  *      *       127.0.0.1            0.0.0.0/0            tcp dpt:80
    0     0 DNAT       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:192.168.92.6:80

查看服务是否正常运行

[root@localhost ~]# podman inspect httpd | grep -i address
            "IPAddress": "192.168.92.6",
            "GlobalIPv6Address": "",
            "MacAddress": "ae:4b:20:26:b1:aa",
            "LinkLocalIPv6Address": "",
                    "IPAddress": "192.168.92.6",
                    "GlobalIPv6Address": "",
                    "MacAddress": "ae:4b:20:26:b1:aa",
[root@localhost ~]# curl 192.168.92.6
<html><body><h1>It works!</h1></body></html>

页面访问
在这里插入图片描述
清空防火墙规则

  • iptables -t nat -F:指定表清空
  • iptables –flush:刷新
  • iptables -t nat -nvL:查看指定规则表
[root@localhost ~]# iptables -t nat -F
[root@localhost ~]# iptables --flush
[root@localhost ~]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-4533b65d6aadf8714d7c3749 (0 references)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-HOSTPORT-SETMARK (0 references)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-HOSTPORT-MASQ (0 references)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-HOSTPORT-DNAT (0 references)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-b823093c81076a7b3058c742 (0 references)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-DN-b823093c81076a7b3058c (0 references)
 pkts bytes target     prot opt in     out     source               destination         

重新加载防火墙规则

[root@localhost ~]# podman network reload httpd
1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171

[root@localhost ~]# iptables -t nat -nvL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-DNAT  all  --  *      *       0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-MASQ  all  --  *      *       0.0.0.0/0            0.0.0.0/0            /* CNI portfwd requiring masquerade */
    0     0 CNI-b823093c81076a7b3058c742  all  --  *      *       192.168.92.6         0.0.0.0/0            /* name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-DNAT  all  --  *      *       0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain CNI-4533b65d6aadf8714d7c3749 (0 references)
 pkts bytes target     prot opt in     out     source               destination         

Chain CNI-HOSTPORT-SETMARK (2 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 MARK       all  --  *      *       0.0.0.0/0            0.0.0.0/0            /* CNI portfwd masquerade mark */ MARK or 0x2000

Chain CNI-HOSTPORT-MASQ (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 MASQUERADE  all  --  *      *       0.0.0.0/0            0.0.0.0/0            mark match 0x2000/0x2000

Chain CNI-HOSTPORT-DNAT (2 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-DN-b823093c81076a7b3058c  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            /* dnat name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */ multiport dports 80

Chain CNI-b823093c81076a7b3058c742 (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.92.0/24      /* name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */
    0     0 MASQUERADE  all  --  *      *       0.0.0.0/0           !224.0.0.0/4          /* name: "network" id: "1e0fcb197f3a4e2cded0d7cab7360942ae261e6c608ebe5c3b30449280200171" */

Chain CNI-DN-b823093c81076a7b3058c (1 references)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 CNI-HOSTPORT-SETMARK  tcp  --  *      *       192.168.92.0/24      0.0.0.0/0            tcp dpt:80
    0     0 CNI-HOSTPORT-SETMARK  tcp  --  *      *       127.0.0.1            0.0.0.0/0            tcp dpt:80
    0     0 DNAT       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:192.168.92.6:80

八、podman常用命令

podman官网

常用命令 作用
podman attach 附加到正在运行的容器。
podman auto update 根据其自动更新策略自动更新容器
podman build 使用 Containerfile 构建容器映像。
podman commit 根据更改的容器创建新图像。
podman completion 生成 shell 完成脚本
podman container 管理容器。
podman cp 在容器和本地文件系统之间复制文件/文件夹。
podman create 创建一个新容器。
podman diff 检查容器或映像文件系统上的更改。
podman events 监控 Podman 事件
podman exec 在正在运行的容器中执行命令。
podman export 将容器的文件系统内容导出为 tar 存档。
podman generate 基于容器、Pod 或卷生成结构化数据。
podman healthcheck 管理容器的健康检查
podman history 显示镜像的历史记录。
podman image 管理镜像。
podman images 列出本地存储中的镜像。
podman import
podman info 显示 Podman 相关的系统信息.
podman init 初始化一个或多个容器
podman inspect 显示容器、镜像、卷、网络或 pod 的配置。
podman kill 杀死一个或多个容器中的主进程。
podman load 将 tar 存档中的图像加载到容器存储中。
podman login 登录到容器注册表。
podman logout 注销容器注册表。
podman logs 显示一个或多个容器的日志。
podman machine 管理 Podman 的虚拟机
podman manifest 创建和操作清单列表和图像索引。
podman mount 挂载一个工作容器的根文件系统。
podman network 管理 Podman CNI 网络。
podman pause 暂停一个或多个容器。
podman play 根据结构化输入文件播放容器、Pod 或卷。
podman pod 容器组的管理工具,称为 pod。
podman port 列出容器的端口映射。
podman ps 从注册表中拉取镜像。
podman push 将镜像、清单列表或镜像索引从本地存储推送到其他地方。
podman rename 重命名现有容器。
podman restart 重启一个或多个容器。
podman rm 移除一个或多个容器。
podman rmi 删除一个或多个本地存储的镜像。
podman run 在新容器中运行命令。
podman save 将镜像保存到存档。
podman search 在注册表中搜索图像。
podman secret 管理 podman 机密。
podman start 启动一个或多个容器。
podman stats 显示一个或多个容器的资源使用统计的实时流。
podman stop 停止一个或多个正在运行的容器。
podman system 管理 podman。
podman tag 向本地镜像添加附加名称。
podman top 显示容器的运行进程。
podman unmount 卸载工作容器的根文件系统。
podman unpause 取消暂停一个或多个容器。
podman unshare 在修改后的用户命名空间内运行命令。
podman untag 从本地存储的图像中删除一个或多个名称。
podman version 显示 Podman 版本信息。
podman volume 简单的卷管理工具。
podman wait 等待一个或多个容器停止并打印其退出代码。

九、容器的开机自启

9.1 root 用户开机自启

// 运行 nginx 容器
[root@localhost ~]# podman create --name nginx nginx:latest 

[root@localhost ~]# podman ps
CONTAINER ID  IMAGE                           COMMAND               CREATED             STATUS                 PORTS       NAMES
c2f83b88020e  docker.io/library/nginx:latest  nginx -g daemon o...  About a minute ago  Up About a minute ago              nginx

// 生成 nginx 的 service 文件
[root@localhost ~]# podman run -itd --name nginx nginx
c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445

[root@localhost ~]# podman generate systemd --restart-policy=always -t 2 nginx
# container-c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445.service
# autogenerated by Podman 3.4.1-dev
# Wed Dec 15 21:30:52 CST 2021

[Unit]
Description=Podman container-c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445.service
Documentation=man:podman-generate-systemd(1)
Wants=network-online.target
After=network-online.target
RequiresMountsFor=/run/containers/storage

[Service]
Environment=PODMAN_SYSTEMD_UNIT=%n
Restart=always
TimeoutStopSec=62
ExecStart=/usr/bin/podman start c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445
ExecStop=/usr/bin/podman stop -t 2 c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445
ExecStopPost=/usr/bin/podman stop -t 2 c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445
PIDFile=/run/containers/storage/overlay-containers/c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445/userdata/conmon.pid
Type=forking

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


// 指定容器生成 service 文件
[root@localhost ~]# podman generate systemd --files --name nginx
/root/container-nginx.service

// 将当前目录下面的 service 文件移动到 /usr/lib/systemd/system/ 下面去
[root@localhost ~]# mv container-nginx.service /usr/lib/systemd/system/

// 重新加载
[root@localhost ~]# systemctl daemon-reload

// 设置开机自启
[root@localhost ~]# systemctl enable --now  container-nginx
Created symlink /etc/systemd/system/multi-user.target.wants/container-nginx.service → /usr/lib/systemd/system/container-nginx.service.
Created symlink /etc/systemd/system/default.target.wants/container-nginx.service → /usr/lib/systemd/system/container-nginx.service.

// 查看 nginx 服务状态
[root@localhost ~]# systemctl status --now container-nginx
● container-nginx.service - Podman container-nginx.service
   Loaded: loaded (/usr/lib/systemd/system/container-nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2021-12-15 21:27:54 CST; 7min ago
     Docs: man:podman-generate-systemd(1)
 Main PID: 68777 (conmon)
    Tasks: 0 (limit: 23485)
   Memory: 2.5M
   CGroup: /system.slice/container-nginx.service
           ‣ 68777 /usr/bin/conmon --api-version 1 -c c2f83b88020eac6f62ae47a7fbe8a7b2dc4b01c117fff6f05a8b4dcdea41e445 -u c2f83b88020ea>

Dec 15 21:27:54 localhost.localdomain systemd[1]: Starting Podman container-nginx.service...
Dec 15 21:27:54 localhost.localdomain systemd[1]: Started Podman container-nginx.service.

9.2 非根用户容器开机自启

// 创建一个普通用户
[root@localhost ~]# id tom
uid=1000(tom) gid=1000(tom) groups=1000(tom)

// 设置密码
[root@localhost ~]# echo "123" | passwd --stdin tom
Changing password for user tom.
passwd: all authentication tokens updated successfully.

// ssh连接
[root@localhost ~]# ssh tom@192.168.91.137
tom@192.168.91.137's password: 
Last failed login: Wed Dec 15 21:38:47 CST 2021 from 192.168.91.137 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Wed Dec 15 11:14:39 2021

// 运行一个容器,非root用户只能映射1024以上的端口,1024以下的端口只能root用户映射
[tom@localhost ~]$ podman images
REPOSITORY                 TAG         IMAGE ID      CREATED      SIZE
docker.io/library/busybox  latest      ffe9d497c324  7 days ago   1.46 MB
docker.io/library/nginx    latest      f652ca386ed1  13 days ago  146 MB

[tom@localhost ~]$ podman run -itd --name nginx f652ca386ed1
cda4a29c910b27ea184066324a17bebe5b5f6f3f14b3bce7b58311bb70c2d683

// 创建service文件目录结构
[tom@localhost ~]$ mkdir -p ~/.config/systemd/user/

[tom@localhost ~]$ cd .config/systemd/user/
[tom@localhost user]$ pwd
/home/tom/.config/systemd/use

// 生成service文件
[tom@localhost user]$ podman generate systemd --files --new --name nginx 
/home/tom/.config/systemd/user/container-nginx.service

[tom@localhost user]$ ls
container-nginx.service
[tom@localhost user]$ cat container-nginx.service 
# container-nginx.service
# autogenerated by Podman 3.4.1-dev
# Wed Dec 15 21:48:13 CST 2021

[Unit]
Description=Podman container-nginx.service
Documentation=man:podman-generate-systemd(1)
Wants=network-online.target
After=network-online.target
RequiresMountsFor=%t/containers

[Service]
Environment=PODMAN_SYSTEMD_UNIT=%n
Restart=on-failure
TimeoutStopSec=70
ExecStartPre=/bin/rm -f %t/%n.ctr-id
ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --cgroups=no-conmon --rm --sdnotify=conmon --replace -itd --name nginx f652ca386ed1
ExecStop=/usr/bin/podman stop --ignore --cidfile=%t/%n.ctr-id
ExecStopPost=/usr/bin/podman rm -f --ignore --cidfile=%t/%n.ctr-id
Type=notify
NotifyAccess=all

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

// 先停止容器,方便测试开机自启
[tom@localhost user]$ podman stop -l
cda4a29c910b27ea184066324a17bebe5b5f6f3f14b3bce7b58311bb70c2d683
[tom@localhost user]$ podman ps
CONTAINER ID  IMAGE       COMMAND     CREATED     STATUS      PORTS       NAMES

// 重新加载服务,设置开机自启,无根用户启动时需要加上--user
[tom@localhost user]$ systemctl --user daemon-reload
[tom@localhost user]$ systemctl --user enable --now container-nginx.service
Created symlink /home/tom/.config/systemd/user/multi-user.target.wants/container-nginx.service → /home/tom/.config/systemd/user/container-nginx.service.
Created symlink /home/tom/.config/systemd/user/default.target.wants/container-nginx.service → /home/tom/.config/systemd/user/container-nginx.service.

// 查看当前服务状态
[tom@localhost user]$ systemctl status container-nginx.service
● container-nginx.service - Podman container-nginx.service
   Loaded: loaded (/usr/lib/systemd/system/container-nginx.>
   Active: failed (Result: exit-code) since Wed 2021-12-15 >
     Docs: man:podman-generate-systemd(1)
  Process: 112917 ExecStopPost=/usr/bin/podman stop -t 10 n>
  Process: 112103 ExecStop=/usr/bin/podman stop -t 10 nginx>
  Process: 112858 ExecStart=/usr/bin/podman start nginx (co>
 Main PID: 68777 (code=exited, status=0/SUCCESS)

// 容器已经开始运行
[tom@localhost user]$ podman ps
CONTAINER ID  IMAGE                           COMMAND               CREATED         STATUS             PORTS       NAMES
662be228b992  docker.io/library/nginx:latest  nginx -g daemon o...  13 minutes ago  Up 13 minutes ago              nginx

// 服务关闭,容器自动删除
[tom@localhost user]$ systemctl --user stop container-nginx.service
[tom@localhost user]$ podman ps
CONTAINER ID  IMAGE       COMMAND     CREATED     STATUS      PORTS       NAMES

// 服务启动,容器自动创建并运行
[tom@localhost user]$ systemctl --user start container-nginx.service
[tom@localhost user]$ podman ps
CONTAINER ID  IMAGE                           COMMAND               CREATED        STATUS            PORTS       NAMES
0bf213d3f1c9  docker.io/library/nginx:latest  nginx -g daemon o...  7 seconds ago  Up 7 seconds ago              nginx

[tom@localhost user]$ loginctl user-status tom
tom (1000)
           Since: Wed 2021-12-15 21:40:51 CST; 29min ago
           State: active
        Sessions: *9
          Linger: no
// active表示含有此权限,没有权限会显示linger

// 当普通用户没有systemd权限,可以执行以下命令开启systemd权限
loginctl enable-linger <username>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/5576.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!