You may have heard that Podman V2 has a new RESTful API. This document demonstrates the API using code examples in Python and shell commands. Additional notes are included in the code comments. The provided code was written to be clear vs. production quality.
Requirements
- You have Python >3.4 installed.
- You have installed the Python requests library.
- An IDE for editing Python is recommended.
- Two terminal windows: one for running the Podman service and reviewing debugging information, the second window to run scripts.
- Usage of curl and jq commands are demonstrated.
- You can review connection URLs here.
Getting started
The service
For these examples, we are running the Podman service as a normal user and on an unsecured TCP/IP port number.
For production, the Podman service should use systemd's socket activation protocol. This allows Podman to support clients without additional daemons and secure the access endpoint.
The following command runs the Podman service on port 8080 without timing out. You will need to type ^C into this terminal window when you are finished with the tutorial.
# podman system service tcp:localhost:8080 --log-level=debug --time=0
In addition to the TCP socket demonstrated above, the Podman service supports running under systemd's socket activation protocol and Unix domain sockets (UDS).
[ You might also like: Sneak peek: Podman's new REST API ]
Python code
Info resource
The following shows us information about the Podman service and host:
import json
import requests
response = requests.get("http://localhost:8080/v1.40.0/libpod/info")
Deep dive
requests.get()calls the requests library to pass the URL to the Podman service using the GET HTTP method.- The requests library provides helper methods for all the popular HTTP methods.
http://localhost:8080matches the Podman service invocation above./v1.40.0denotes the API version we are using./libpoddenotes that we expect the service to provide alibpod-specific return payload.- Not using this element causes the server to return a compatible payload.
/infospecifies the resource we are querying.
Interesting to read, but without output, how do we know it worked?
Getting output
Append the lines below, and you can now see the version of Podman running on the host:
response.raise_for_status()
info = json.loads(response.text)
print(info.version.Version)
raise_for_status()raises an exception if status code is not between 200 and 399.json.loads()decodes the body of the HTTP response into an object/dictionary.
When executed, the output is:
2.1.0-dev
The following works from the shell:
$ curl -s 'http://localhost:8080/v1.40.0/libpod/info' | jq .version.Version
"2.1.0-dev"
Listing containers
import json
import requests
response = requests.get("http://localhost:8080/v1.40.0/libpod/containers/json?all=true")
response.raise_for_status()
ctnrs = json.loads(response.text)
for c in ctnrs:
print(c.Id)
json.loads() decodes the HTTP body into an array of objects/dictionaries, the program then prints each container Id. For example:
$ curl -s 'http://localhost:8080/v1.40.0/libpod/containers/json?all=true' | jq .[].Id
"81af11ef7188a826cb5883330525e44afea3ae82634980d68e4e9eefc98d6f61"
If the query parameter all=true had not been provided, then only the running containers would have been listed. The resource queries and parameters for the API are documented here.
Something useful
We've looked at a couple of examples, but how about something a little more useful? You have finished developing the next great container, and the script below will remove everything from your local storage. (If you want to save on typing clean_storage.py)
#!/usr/bin/env python
import json
import requests
# Clean up local storage by removing all containers, pods, and images. Any error will
# abort the process
confirm = input("Really delete all items from storage? [y/N] ")
if str(confirm).lower().strip() != 'y':
exit(0)
# Query for all pods in storage
response = requests.get("http://localhost:8080/v1.40.0/libpod/pods/json")
response.raise_for_status()
pods = json.loads(response.text)
# Workaround for https://github.com/containers/podman/issues/7392
if pods is not None:
for p in pods:
# For each container: delete container and associated volumes
response = requests.delete(f"http://localhost:8080/v1.40.0/libpod/pods/{p['Id']}?force=true")
response.raise_for_status()
print(f"Removed {len(pods)} pods and associated objects")
else:
print(f"Removed 0 pods and associated objects")
# Query for all containers in storage
response = requests.get("http://localhost:8080/v1.40.0/libpod/containers/json?all=true")
response.raise_for_status()
ctnrs = json.loads(response.text)
for c in ctnrs:
# For each container: delete container and associated volumes
print(c.keys())
response = requests.delete(f"http://localhost:8080/v1.40.0/libpod/containers/{c['Id']}?force=true&v=true")
response.raise_for_status()
print(f"Removed {len(ctnrs)} containers and associated objects")
# Query for all images in storage
response = requests.get("http://localhost:8080/v1.40.0/libpod/images/json")
response.raise_for_status()
imgs = json.loads(response.text)
for i in imgs:
# For each image: delete image and any associated containers
response = requests.delete(f"http://localhost:8080/v1.40.0/libpod/images/{i['Id']}?force=true")
response.raise_for_status()
print(f"Removed {len(imgs)} images and associated objects")
[ Getting started with containers? Check out this free course. Deploying containerized applications: A technical overview. ]
Summary
I hope you find this helpful. The API documentation provides you with all the resources and required methods. The input and output bodies are included as well as the status codes.
The Podman code is under heavy development and we welcome your input with issues and pull requests on the project's GitHub page.
저자 소개
Experienced senior software developer/system administrator with 37 years of technical experience. Deep understanding of UNIX/Linux, TCP/IP networking, Internet and software development. Has worked for a diverse set of organizations from large government agencies (NASA, NARA) to 5 person startups. Always applying experience and knowledge to solve the technical challenges of the organization.
Designing and implementing SAS applications (Cloud) on a RAIN architecture with innovative indexing technology for supporting the business rules and logic. This allows for both high performance and horizontal scaling. Examples: DICOM Grid, Inc, and Red Hat OpenShift.
유사한 검색 결과
Red Hat Enterprise Linux Long-Life Add-On: 지원 종료 걱정 없는 RHEL 소개
인프라를 Red Hat Lightspeed에 어떻게 연결해야 할까요?
Scaling with Orchestrators | Compiler
Container Roundup | Compiler
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
가상화
온프레미스와 클라우드 환경에서 워크로드를 유연하게 운영하기 위한 엔터프라이즈 가상화의 미래