Issue
I'm trying to manage docker via PHP curl requests. (Using Ubuntu 15.10)
I have followed API documentation but it bit confusing and also followed a few online tutorials but no luck.
This is what I have done so far, stopped docker daemon and added
script
/usr/bin/docker -H tcp://127.0.0.1:4243 -d
end script
to
/etc/init/docker.conf
Docker daemon started
This is My PHP script
function post_to_url($url, $data, $headers) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout in seconds
curl_setopt($ch, CURLOPT_URL, $url);
if ($headers != '') {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_POST, 1);
if ($data != '') {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
if ($return == '') {
return curl_getinfo($ch, CURLINFO_HTTP_CODE);
} else {
return $return;
}
curl_close($ch);
}
//Sample API request
echo post_to_url('http://127.0.0.1:4243/containers/json', '', '');
But I did not able to get any output via CURL request?
What I'm missing here?
Solution
Finally I was able to figure that out.
In /etc/defaults/docker
I put
DOCKER_OPTS='-H tcp://127.0.0.1:4243 -H unix:///var/run/docker.sock'
(Use 0.0.0.0
instead of 127.0.0.1
to access API via any host)
My PHP function in the question is not compatible with REST API,
So I have used following function (Source - This)
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
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_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
And called above function:
echo CallAPI('GET', 'http://127.0.0.1:4243/images/json', $data = false)
and it worked!
Opening up Docker API to the public is a major security risk, so I have used IP address 127.0.0.1
instead of 0.0.0.0
, so my PHP script can still access it.
Answered By - M_R_K Answer Checked By - Clifford M. (WPSolving Volunteer)