【问题标题】:Docker commands via php shell_exec通过 php shell_exec 的 Docker 命令
【发布时间】:2015-07-17 19:25:45
【问题描述】:

我正在尝试从我的 index.php 运行命令:

$output = shell_exec('docker images');

然后输出结果,

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

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

似乎我无法通过 php 运行任何 docker cmd。

如何正确操作?

【问题讨论】:

  • 你是在容器外运行 PHP 吗?
  • 是的。我尝试从主机上的网络浏览器运行它。
  • 你的容器里有什么?它是网络服务器吗?如果是这样,由于端口冲突等原因,将无法在浏览器中查看输出。

标签: php shell docker ubuntu-14.04


【解决方案1】:

我做了以下工作:

  1. /var/www/html/ 上创建了一个名为 index.php 的 php 文件,内容如下:

    <?php
        echo '<pre>';
        $content = system('sudo docker images', $ret);
        echo '</pre>';
    ?>
    
  2. 使用 visudo 编辑 sudoers 文件,在末尾添加以下行:

    www-data ALL=NOPASSWD: /usr/bin/docker
    
  3. 检查了http://localhost/index.php,它成功了!

你甚至可以用它来构建和运行容器,希望它对你有用。

【讨论】:

    【解决方案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/
    

    就是这样!

    希望对你有帮助

    【讨论】:

    • 是的,它有效,但前提是我在控制台中运行它。当我尝试在浏览器中运行它时,我看不到输出结果。
    • 在 WEB 页面中运行此程序可能存在安全问题
    • 我几乎找到了解决方案。我修改了文件 sudoers (sudo visudo),在末尾添加:www-data ALL=NOPASSWD: ALL。 PHP 现在运行我的 docker 命令。我知道这很危险,但是如果我将其更改为: www-data ALL=NOPASSWD: /usr/bin/php, /usr/bin/php5 它仍然无法正常工作。还有什么想法? (unix.stackexchange.com/questions/115054/…)
    • 我的 var/log/apache2/error.log 包含:sudo:不存在 tty,也没有指定 askpass 程序
    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2016-07-16
    • 1970-01-01
    相关资源
    最近更新 更多