Executing PHP curl from inside of the container via docker socket

Viewed 17

I'm facing very similar problem to the one described here: cURL request to Unix socket from php. I'm running a docker container and I want to execute the equivalent of curl --unix-socket /var/run/docker.sock http://localhost/v1.40/containers/json in order to get a list of containers created on host. I've tried both way suggested in the topic, although I'm not able to get any response - STDERR doesn't produce anything as well.

My code:

<?php
function callAPI($method, $url, $data){
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, "/var/run/docker.sock");
   curl_setopt($curl, CURLOPT_VERBOSE, true);
   switch ($method){
      case "POST":
         curl_setopt($curl, CURLOPT_POST, 1);
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
         break;
      case "PUT":
         curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);                              
         break;
      default:
         if ($data)
            $url = sprintf("%s?%s", $url, http_build_query($data));
   }
   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json'
   ));
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   // EXECUTE:
   $result = curl_exec($curl);
   // echo $result;
   print_r($result);
   if(!$result){die("Connection Failure");}
   $info = curl_getinfo($curl);
   print_r($info);
   curl_close($curl);
   return $result;
}

$get_data = callAPI("GET","http://localhost/v1.40/containers/json", false);


print_r($get_data);
$response = json_decode($get_data, true);
$errors = $response['response']['errors'];
print_r($response);
echo $data;
echo $errors;
?>

I usually end up with "Connection Failure" or the following curl_getinfo() output: Array ( [url] => http://localhost/v1.40/containers/json [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0 [namelookup_time] => 2.1E-5 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [redirect_url] => [primary_ip] => [certinfo] => Array ( ) [primary_port] => 0 [local_ip] => [local_port] => 0 [http_version] => 0 [protocol] => 0 [ssl_verifyresult] => 0 [scheme] => )

Could you help me find what's wrong with my code? Standard bash-based curl produces the correct output...

0 Answers
Related