Podman 创建容器时出错:[POST 操作失败]

问题描述 投票:0回答:1

我有一个 podman 容器,其中有一个 python 文件来运行脚本,该脚本创建特定 image_name 和 container_name 的容器。

按照以下说明重新创建问题:

mkdir trial
cd trial

touch Dockerfile
touch create_container.py

Python 文件内容:

from podman import PodmanClient
import sys

def create_container(image_name, container_name):
    with PodmanClient() as client:
        try:
            # Create and start the container
            container = client.containers.create(image=image_name, name=container_name)
            container.start()
            print(f"Container '{container_name}' created and started successfully.")
            print(f"Container ID: {container.id}")
        except Exception as e:
            print(f"Error creating container: {e}")
            sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit(1)

    image_name = sys.argv[1]
    container_name = sys.argv[2]
    create_container(image_name, container_name)

Docekr 文件:

FROM python:3.8.5-slim-buster
WORKDIR /app

# Copy the Python script into the container
COPY create_container.py .

# Install the Podman library
RUN pip install podman

# Set the entrypoint to run the Python script
ENTRYPOINT ["python", "create_container.py"]

运行:

podman build -t test
podman run --rm --privileged --network host -v /run/podman/podman.sock:/run/podman/podman.sock test <Name of the image> trial

出现错误:

Error creating container: http://%2Ftmp%2Fpodmanpy-runtime-dir-fallback-root%2Fpodman%2Fpodman.sock/v5.2.0/libpod/containers/create (POST operation failed)

我解决问题的方法: 1)认为 Podmanclient 正在获取随机套接字位置,因此在 python 文件中使用 Podmanclient 时硬编码该位置。

...  
   with PodmanClient(uri='unix:///run/podman/podman.sock') as client:
  .
 .
.
  1. 最初在 /run/podman/podman.sock 处遇到文件权限问题,因此更改了普通用户的所有权和文件权限。

3)Podman 服务会在一段时间后变得不活动,因此将 /usr/lib/systemd/system/podman.service 中的文件更改为下面提到的代码:

[Unit]
Description=Podman API Service
Requires=podman.socket
After=podman.socket
Documentation=man:podman-system-service(1)
StartLimitIntervalSec=0

[Service]
Type=exec
KillMode=process
Environment=LOGGING="--log-level=info"
ExecStart=/usr/bin/podman $LOGGING system service tcp:0.0.0.0:8080 --time=0

[Install]
WantedBy=default.target

也尝试将 tcp url 更改为 127.0.0.1(loclhost),但没有成功。

  1. 作为最后的手段,我也卸载并重新安装了 podman。 注意我可以使用 Podmanclient 的 python 脚本在外部创建一个容器,所以我认为这一定是 podman 的问题,而不是 podman python 包的问题。

谢谢你。

在容器外部运行的代码。即使我在 create_container.py 文件中添加额外的 os.environ ,问题也没有改变。 导入操作系统 导入podman

# Set the Podman socket (adjust if necessary)
os.environ['PODMAN_SOCKET'] = '/run/user/1000/podman/podman.sock'

def create_container(image_name, container_name, command):
    try:
        print(f'Starting Container: {image_name}')
        print("Command running: " + command)

        client = podman.PodmanClient()  # Initialize Podman client

        # Use bind mount instead of named volume
        volume_src = '/home/vinee/myprojects/trial'  # Host directory
        volume_dst = '/edge/'  # Container mount point
        
        # Ensure the source path exists
        if not os.path.exists(volume_src):
            raise ValueError(f"Source volume path does not exist: {volume_src}")

        # Create the mount configuration
        bind_volumes = [
            {
                'type': 'bind',
                'source': volume_src,
                'target': volume_dst,
                'read_only': False  # Set to True if you want read-only access
            }
        ]

        # Create and start the container
        container = client.containers.run(
            image=image_name,
            name=container_name,
            command=command,
            detach=True,
            mounts=bind_volumes,  # Use the mounts configuration
            auto_remove=False,
            network_mode="host",
            shm_size=2147483648,
            privileged=True,
            devices=['/dev/nvidia0'],  # Specify device paths as needed
            environment={'TZ': 'Asia/Kolkata'}
        )

        print(f"Container ID: {container.id}")
        container_data = {
            'containername': container_name,
            'containerid': container.id,
            'imagename': image_name,
            'status': "RUNNING"
        }
        print("Container Information:")
        print(container_data)

        print("-" * 10 + " Container information updated successfully " + "-" * 10)
        print("Container Started Successfully")
        return {'message': 'Success'}

    except podman.errors.PodmanError as e:
        print(f"Podman specific error: {e}")
    except Exception as e:
        print(f"General error creating container: {e}")
    return {'message': 'Error creating container'}

if __name__ == "__main__":
    result = create_container(
        "pythontest",
        "aA993dc42c504f4e853261105a2351bd",
        "python3 test.py"
    )
    print(result)
python pypi podman podman-compose
1个回答
0
投票

我没有尝试弄乱任何权限或单元文件,但使用 Dockerfile 中的容器没有任何问题。 您确定您不只是错过了

base_url
论点吗?

我运行了新建的容器

test
并安装在(无根)podman 套接字中。
我没有运行你的脚本,而是交互地使用了
PodmanClient

$ podman run -it --rm --entrypoint='python3' --privileged -v /run/user/1000/podman/podman.sock:/run/podman/podman.sock test
Python 3.8.5 (default, Sep 10 2020, 16:58:22)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from podman import PodmanClient
>>> with PodmanClient(base_url="http+unix:///run/podman/podman.sock") as client:
...    container = client.containers.run("busybox", ["sleep","infitity"],
...    detach=True, name="sleeper")
...
>>>

退出Python容器并验证

sleeper
容器创建:

$ podman ps --filter=name=sleeper
CONTAINER ID  IMAGE                             COMMAND         CREATED         STATUS         PORTS       NAMES
c98f94c5c76f  docker.io/library/busybox:latest  sleep infitity  17 seconds ago  Up 17 seconds              sleeper
$
© www.soinside.com 2019 - 2024. All rights reserved.