Bash脚本执行Docker容器操作并提取容器IP地址

时间:2013-12-05 06:31:16

标签: linux bash docker

我正在尝试编写一个Linux bash脚本,该脚本创建并运行运行简单python Web服务器的docker容器,提取容器IP地址并通过浏览器向服务器发出HTTP请求。我的脚本似乎有些错误,我需要帮助来编辑它。我是bash脚本的新手。我使用的是Ubuntu 13.10

我的剧本:

#!/bin/bash
for i in {1..2}
do
   echo "Creating and Running Container $i "
   sudo docker run -name $i PythonServer
   IP=sudo docker inspect $i | grep IPAddress | cut -d '"' -f 4
   echo "Ip Address is:"
   echo "${IP}"
   xdg-open 'http://$IP:7111/execute'
done

编辑:代码的第6行似乎不起作用,因为echo "${IP}"给出了空白输出。我想将sudo docker inspect $i | grep IPAddress | cut -d '"' -f 4的结果分配给IP变量,即我想捕获所创建容器的IP地址,并在xdg-open 'http://$IP:7111/execute'中使用它来动态生成HTTP请求。但是我没有得到应该编写这个bash脚本行的正确格式:IP=sudo docker inspect $i | grep IPAddress | cut -d '"' -f 4

IP

中使用xdg-open 'http://$IP:7111/execute'值的正确格式是什么?

上面提到的脚本目前在执行时显示此消息:

vishal@bl-lin-01:~/docker/PythonServer/new$ ./BashScript.sh
Creating and Running Container 1 
WARNING: Docker detected local DNS server on resolv.conf. Using default external servers: [8.8.8.8 8.8.4.4]
^Cserving at port 7111
Traceback (most recent call last):
File "/scripts/InitScript.py", line 40, in <module>
httpd.serve_forever()
File "/usr/lib/python2.7/SocketServer.py", line 225, in serve_forever
r, w, e = select.select([self], [], [], poll_interval)
KeyboardInterrupt
unknown option: 1

valid options are:
-license
-copyright
-crlf
-end
-link
-path_name
-tab
-ascii
-apple_macro
-assert_macro
-minmax
-unnamed
default is all checks on; otherwise options specify desired checks
Ip Address is:

感谢。

2 个答案:

答案 0 :(得分:0)

此编辑的Bash脚本现在正常工作..

#!/bin/bash
for i in {1..2}
do
   echo "Creating and Running Container $i "
   sudo docker run -d -name $i PythonServer
   IP=$(sudo docker inspect $i | grep IPAddress | cut -d '"' -f 4)
   echo "Ip Address is:$IP"
   xdg-open "http://$IP:7111/execute"
done

我以守护进程模式运行容器,并使用bash的Command Substitution功能将命令的输出分配给变量IP

答案 1 :(得分:0)

获取docker容器IP地址的最佳方法是

while(rs.next() && i<25){                    
        DTO aux=new DTO();// create aux object here

        aux.setIdVinilo(rs.getInt("id_vinilo"));
        aux.setTitulo(rs.getString("titulo"));
        aux.setAutor(rs.getString("autor"));
        aux.setGenero(rs.getString("genero"));
        aux.setFecha(rs.getInt("fecha"));
        aux.setDiscografica(rs.getString("discografica"));
        aux.setImagen(rs.getString("imagen"));

        historial.add(aux);
        i++;
} 
相关问题