開啟Remote API
docker默認是沒有開啟Remote API的,需要我們手動開啟。編輯/lib/systemd/system/docker.service
文件,
在文件里的ExecStart
參數后面添加-H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock
然后重啟sudo systemctl daemon-reload sudo service docker restart 在瀏覽器查看:
備注:我這里用了 JSONView-for-Chrome插件 ,用git下載下來,chrome設置 - 擴展程序 (地址欄輸入chrome://extensions/)-> 選中 開發模式-> 點擊"加載已解壓的擴展程序" -> 選擇插件目錄(xxx\JSONView-for-Chrome-master\WebContent)
Python API
需要安裝pip3 install docker-py,理論上docker-py可以干所有事情,但實際現在還不不怎么好用
import docker client = docker.DockerClient("http://192.168.100.5:2375") #打印現有的images名稱 #images =client.images.list() #for img in images: #print(img.attrs["RepoTags"][0]) #獲取container for container in client.containers.list(): #print(dir(container)) print("container:"+container.name+" image:"+container.image.attrs["RepoTags"][0]) #拉取鏡像 相當於sudo docker pull alpine image = client.images.pull("alpine") #運行鏡像 如果detach=True,會立即返回一個container對象 container = client.containers.run("alpine", ["touch", "/helloworld"], detach=True) container.wait() #提交新鏡像 image = container.commit("helloworld")
import docker client = docker.DockerClient("http://192.168.100.5:2375") #打印現有的images名稱 #images =client.images.list() #for img in images: #print(img.attrs["RepoTags"][0]) #獲取container for container in client.containers.list(): #print(dir(container)) print("container:"+container.name+" image:"+container.image.attrs["RepoTags"][0]) #拉取鏡像 相當於sudo docker pull alpine image = client.images.pull("alpine") #運行鏡像 如果detach=True,會立即返回一個container對象 container = client.containers.run("alpine", ["touch", "/helloworld"], detach=True) container.wait() #提交新鏡像 image = container.commit("helloworld")
參考:
https://docs.docker.com/develop/sdk/examples/
https://github.com/docker/docker-py
https://letong.gitbooks.io/docker/content/API/python_api.html