用php的shell_exec执行Docker命令

3
我正在尝试从我的index.php运行命令:
$output = shell_exec('docker images');

然后输出结果,

或者以相同的方式运行新容器:

$output = shell_exec('docker run hello-world');

看起来我无法通过php运行任何docker命令。

应该如何正确处理?


你是否在容器外运行PHP? - Jay Blanchard
是的。我尝试从主机上的Web浏览器运行它。 - YasiuMaster
你的容器里面是什么?是一个Web服务器吗?如果是,由于端口冲突等原因,无法在浏览器中看到输出。 - Jay Blanchard
2个回答

4

我按照以下步骤使其工作:

  1. Created a php file called index.php on /var/www/html/ with this content:

    <?php
        echo '<pre>';
        $content = system('sudo docker images', $ret);
        echo '</pre>';
    ?>
    
  2. Edited sudoers file with visudo, adding the following line at the end:

    www-data ALL=NOPASSWD: /usr/bin/docker
    
  3. Checked http://localhost/index.php and it worked!

enter image description here

你甚至可以使用它构建和运行容器,希望它能对你有所帮助。

2
你可以这样做:
vi rd.php

将这段内容放入rd.php文件中。
<?php 
$output = shell_exec('RET=`docker run hello-world`;echo $RET');
echo $output;

现在你可以运行。
php rd.php

您可以查看结果:
Hello from Docker. This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (Assuming it was not already locally available.) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash For more examples and ideas, visit: http://docs.docker.com/userguide/

这就是全部内容!

希望这能帮到你。


是的,它可以运行,但只有在控制台中运行时才有效。当我尝试在浏览器中运行时,无法看到输出结果。 - YasiuMaster
可能在 WEB 页面中运行此代码存在安全问题。 - João Paraná
我已经快找到解决方案了。我修改了sudoers文件(sudo visudo),在末尾添加了:www-data ALL=NOPASSWD: ALL。现在PHP可以运行我的docker命令了。 我知道这很危险,但如果我将其更改为: www-data ALL=NOPASSWD: /usr/bin/php,/usr/bin/php5 它仍然无法工作。还有其他想法吗?(http://unix.stackexchange.com/questions/115054/php-shell-exec-permission-on-linux-ubuntu) - YasiuMaster
我的 var/log/apache2/error.log 包含: sudo: no tty present and no askpass program specified - YasiuMaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接