1.docker宿主機配置文件修改
1
2
3
|
$vim /etc/default/docker #再已有OPTS中添加 DOCKER_OPTS= "-H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock" 使得可以通過tcp的2375端口連接到docker守護進程中,第二個-H及之后的內容可以省略 |
2.安裝docker-py
1
|
$sudo pip install docker - py |
3.編寫api腳本
參考文檔
http://docker-py.readthedocs.org/en/latest/
1
2
3
4
5
6
7
8
9
|
from docker import Client d=Client(base_url= 'tcp://10.109.252.221:2375' ,version= 'auto' ,timeout=10) #注意填寫url端口版本號和超時時間 def containerCreate(** command ): container=d.create_containter(** command ) print container #這里使用非關鍵字可變長參數**command,可以將需要使用的參數以字典形式傳輸,并且函數會自動識別字典內的參數 containerCreate(**{ 'name' : 'test1' , 'command' : '/bin/bash' , 'image' : 'ubuntu' }) #這里注意要使用**雙星號傳實參,不然會出錯。 |
4.端口綁定、磁盤掛載和link操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
def containerCreate(port, volume, link, * * command): # 創建容器 command[ 'host_config' ] = d.create_host_config(port_bindings = port, binds = [volume],links = link) container = d.create_container( * * command) d.start(container = container.get( 'Id' )) print container containerCreate( * * { 'name' : 'test1' , 'stdin_open' : True , 'tty' : True , 'command' : '/bin/bash' , 'image' : '10.109.252.221:5000/ubuntu' , 'ports' :[ 8008 ], 'port' :{ 8008 : 9995 }, 'volume' : '/home/ubuntu/test:/test' , 'link' :{ 'mysql' : 'db' }}) #其中,ports必須聲明,port和volume是我自己寫的,用來傳遞參數 #ports聲明容器開放的端口,port中,第一個是容器端口,后一個是主機端口,正好與dokcer run -p相反 #link操作需要傳遞字典或元組,我自己使用元組沒有成功,用字典即可。 |
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/l6807718/article/details/51242693