Giter Site home page Giter Site logo

docker-php's Introduction

No longer maintained

I'm backing off maintaining this library due to a lack of motivation, time and usage of docker, contact me on twitter https://twitter.com/joelwurtz if you wish to take over this repository (or just do a fork).

Docker PHP

Docker PHP (for lack of a better name) is a Docker client written in PHP. This library aim to reach 100% API support of the Docker Engine.

The test suite currently passes against Docker Remote API v1.25 to v1.36.

Documentation Status Latest Version Software License Build Status Code Coverage Quality Score Total Downloads #docker-php on Slack

Installation

The recommended way to install Docker PHP is of course to use Composer:

composer require docker-php/docker-php

Docker API Version

By default it will use the last version of docker api available, if you want to fix a version (like 1.25) you can add this requirement to composer:

composer require "docker-php/docker-php-api:4.1.25.*"

Usage

See the documentation.

Unit Tests

Setup the test suite using Composer if not already done:

$ composer install --dev

Run it using PHPUnit:

$ composer test

Contributing

Please see CONTRIBUTING for details.

Credits

This README heavily inspired by willdurand/Negotiation by @willdurand. This guy is pretty awesome.

License

The MIT License (MIT). Please see License File for more information.

docker-php's People

Contributors

atroy avatar babacooll avatar boran avatar casualjim avatar dbjpanda avatar deweller avatar ericpoe avatar hacfi avatar iamluc avatar jakubsacha avatar jeffturcotte avatar joelwurtz avatar krzaczek avatar leesaferite avatar marcvdm avatar micmania1 avatar mycroft avatar nubs avatar patrickmarie avatar pborreli avatar petehalverson avatar r0b1n avatar rowdyelectron avatar ryanaslett avatar sammousa avatar schmunk42 avatar sibprogrammer avatar tasuki avatar ubermuda avatar willdurand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docker-php's Issues

ContainerManager start, stop and remove should block.

Some of the commands in ContainerManager do not block. Specifically: start, stop, and remove. For example, this means that the call to inspect() within start (or even a call to inspect() after start()) does not work because it is called before the container has finished initializing. This makes scripting with these methods not pleasant.

The ability to perform these actions asynchronously would be nice, but 99% of the time, you want them to block. Blocking should be the default behavior, and maybe the only behavior at this stage of development.

I implemented a somewhat hacky fix: ensuring that the response stream is completely retrieved and closed before continuing. See it here: jeffturcotte/docker-php@f76dfb6. I have a feeling there is probably a better way to accomplish this, so I'm looking for suggestions. I can implement a real fix after discussion.

Tag a new version

Would it be possible to tag a new version of docker-php? There's a lot of improvement on the master branch since the last tag.

Improve error messages

When exceptions are thrown provide better feedback messages what exactly is happening. This could also be solved with some sort of validator mechanism.

Warnings with stream_get_meta_data()

Hi,

nice job, your tool looks really amazing :)

the variable $socket is never tested in the DockerAdapter, that's why I get warnings when stream_get_meta_data() is called.

Warning: stream_get_meta_data() expects parameter 1 to be resource, boolean given in phar:///home/data/www/jeff/misc/halstead/jolici.phar/vendor/stage1/docker-php/src/Docker/Http/Adapter/DockerAdapter.php on line 107

I think I'll fix this issue tomorrow.

Container create setCmd() string[]

Hi,

I'm having problems creating a new container when passing array of string to setCmd() method

$containerConfig = new \Docker\API\Model\ContainerConfig();
$containerConfig->setName('test');
$containerConfig->setTty(true);
$containerConfig->setCmd(['ls', '-la']);
$manager->create($containerConfig);

This results in an Internal Server Error

#0 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/php-http/plugins/src/ErrorPlugin.php(27): Http\Client\Plugin\ErrorPlugin->transformResponseToException(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/php-http/promise/src/FulfilledPromise.php(37): Http\Client\Plugin\ErrorPlugin->Http\Client\Plugin\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/php-http/plugins/src/ErrorPlugin.php(28): Http\Promise\FulfilledPromise->then(Object(Closure))
#3 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/php-http/plugins/src/PluginClient.php(130): Http\Client\Plugin\ErrorPlugin->handleRequest(Object(GuzzleHttp\Psr7\Request), Object(Closure), Object(Closure))
#4 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/php-http/plugins/src/PluginClient.php(144): Http\Client\Plugin\PluginClient->Http\Client\Plugin\{closure}(Object(GuzzleHttp\Psr7\Request))
#5 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/php-http/plugins/src/PluginClient.php(84): Http\Client\Plugin\PluginClient->Http\Client\Plugin\{closure}(Object(GuzzleHttp\Psr7\Request))
#6 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/stage1/docker-php/src/DockerClient.php(41): Http\Client\Plugin\PluginClient->sendRequest(Object(GuzzleHttp\Psr7\Request))
#7 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/vendor/stage1/docker-php/generated/Resource/ContainerResource.php(72): Docker\DockerClient->sendRequest(Object(GuzzleHttp\Psr7\Request))
#8 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/core/lib/Queue/Task/Project/Render.php(32): Docker\API\Resource\ContainerResource->create(Object(Docker\API\Model\ContainerConfig), Array)
#9 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/core/lib/Queue/Jobs/Abstract.php(52): Queue_Task_Project_Render->fire(Object(Queue_Jobs_Beanstalkd), Array)
#10 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/core/lib/Queue/Jobs/Beanstalkd.php(48): Queue_Jobs_Abstract->resolveAndFire(Array)
#11 /Users/pawel/Documents/_Projekty/gitlab/printu/printu/bin/queue/beanstalkd.php(76): Queue_Jobs_Beanstalkd->fire()
#12 {main}===========================================

And an docker error

time="2016-01-26T17:06:45.263342062+01:00" level=info msg="POST /containers/create?name=test" 
time="2016-01-26T17:06:45.295238709+01:00" level=error msg="Handler for POST /containers/create returned error: json: cannot unmarshal array into Go value of type string" 
time="2016-01-26T17:06:45.295299220+01:00" level=error msg="HTTP Error" err="json: cannot unmarshal array into Go value of type string" statusCode=500 

Am i missing something? Running dev-master of docker-php. Starting a container with setCmd('string') works ok.

ContainerManager->interact()

How is this feature used?
Should a script like:
$container = $manager->find('mycontainer');
$manager->interact($container);

allow one to connect to into a container in the same way as nsenter or docker exec?

PhpDoc FQCN vs namespaces

Working on some PRs I noticed that the PhpDocs always use the full FQCN (see https://github.com/stage1/docker-php/blob/master/src/Docker/Docker.php#L30)

Example:
https://github.com/stage1/docker-php/blob/master/src/Docker/Docker.php#L30

    /**
     * @var \Docker\Manager\ImageManager
     */
    private $imageManager;

instead of just @var ImageManager.

Do you want to keep this or can I create a PR getting rid of the unnecessary long FQCN names? If so, should I add the use statements for classes which aren’t used in the PHP code but just in the PhpDocs?

See http://www.phpdoc.org/docs/latest/guides/types.html#class-name that this is valid PhpDoc.

PHP 7 support

It looks like the stream filters are not working with PHP 7.

Warning: stream_filter_append(): Filter failed to process pre-buffered data in /app/vendor/stage1/docker-php/src/Docker/Http/Adapter/DockerAdapter.php on line 221

Then, Guzzle returns the following error:

error.CRITICAL: Failed to handle a message {"exception":"[object] (GuzzleHttp\\Exception\\ParseException(code: 0): Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON at /app/vendor/guzzlehttp/guzzle/src/Message/Response.php:137)...

Boolean values in Docker API

While implementing isolated tests I have noticed some issues.
Docker API supports boolean values as 1/true/True or 0/false/False only (as well as doc says). Part of current implementation doesn't follows requirements, false becomes empty string in request ?force=&noprune=.
I offer to cast these values to 0 or 1 explicitly.
r0b1n@aa51198

/tmp/docker-certfile flooding

Each run of my script create new file in /tmp folder with my cert and private key that i use to connect to docker api. If omitt security issue, there is problem with running out of inodes.

My script can by pretty simple:

$client = DockerClient::createWithEnv();
$docker = new Docker($client);

DOCKER_TLS_VERIFY = 1
DOCKER_PEER_NAME = "docker.myserver.dev"
DOCKER_HOST = "tcp://192.168.1.1:2376"
DOCKER_CERT_PATH = /etc/myapp/

container by its name (not id)

Having hacked together a class for managing docker from php/Drupal, I've just come across your library, which has tests and is better written :-). So time to dive in and have a look!

Q1:
Is there a way to find a container by its name (not id), do it could be stopped in a snippet like this:
$client = new Docker\Http\DockerClient(array(), $this->dserver);
$this->docker = new Docker\Docker($client);
$manager = $this->docker->getContainerManager();
$container = $manager->find('mycontainer1');
$manager->stop($container);

Q2:
is there a way of logging function calls+results or docker api calls in the library? e.g. when running the snippet above nothing happens and no exception is thrown .
How do you trace though the code when running on a webserver for example?

json: cannot unmarshal object into Go value of type []string

Hi,

I’ve got a json: cannot unmarshal object into Go value of type []string error only when I’m trying to run a new container with Docker-PHP.

Here is my Docker version:

Docker version 1.7.1, build 786b29d

I’m running my application in a Docker container which use the docker socket as volume.

    "Volumes": {
        "/data": "/var/www/littleship",
        "/var/run/docker.sock": "/run/docker.sock"
    },
    "VolumesRW": {
        "/data": true,
        "/var/run/docker.sock": true
    },  

And here is my Symfony action to create a container (https://github.com/ambroisemaupate/littleship/blob/master/src/AM/Bundle/DockerBundle/Controller/ContainerController.php#L144):

    public function addAction(Request $request)
    {
        if (!$this->isGranted('ROLE_SUPER_ADMIN')) {
            throw $this->createAccessDeniedException();
        }

        try {
            $docker = $this->get('docker');
            $cManager = $docker->getContainerManager();
            $iManager = $docker->getImageManager();

            $form = $this->createForm(new ContainerType($iManager, $cManager));

            $form->handleRequest($request);

            if ($form->isValid()) {
                $data = $form->getData();
                $newCont = new Container([
                    'HostConfig' => [
                        'Links' => $data['links'],
                        'VolumesFrom' => $data['volumes_from'],
                        'PublishAllPorts' => (boolean) $data['publish_ports'],
                        'RestartPolicy' => [
                            'Name' => $data['restart_policy'],
                            'MaximumRetryCount' => 0
                        ]
                    ]
                ]);
                $newCont->setImage($data['image']);
                $newCont->setExposedPorts($this->getExposedPorts($data['ports']));
                $newCont->setName($data['name']);
                $newCont->setEnv($data['env']);
                $cManager->run($newCont, null, [], true);

                return $this->redirect($this->generateUrl('am_docker_container_list'));
            }

            $assignation['form'] = $form->createView();
        } catch (RequestException $e) {
            $assignation['error'] = $e->getMessage();
        }

        return $this->render('AMDockerBundle:Container:add.html.twig', $assignation);
    }

This action perfectly worked before Docker 1.7.1 upgrade, and other actions still work (stop, restart and remove containers). Do you have any idea ? Do you need more informations ?

Thanks!
Sincerely,

Ambroise

Container or image import?

Docker-php has a container export() to a tar file. There does not seem to be a corresponding import() though. Presumably it would be an image import().

Docker command line: http://docs.docker.com/reference/commandline/cli/#import
API, looks like /images/create might be the way to do this? http://docs.docker.com/reference/api/docker_remote_api_v1.16/#create-an-image

  • "fromSrc – source to import. The value may be a URL from which the image can be retrieved or - to read the image from the request body."

Has anyone looked into this? An branches around with such a function?
In ImageManager.php, pull() uses /create, it would be similar to that but feeding the tar file into the request body?

"Unable to parse JSON" on inspect()

PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\ParseException' with message 'Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON' in ../vendor/guzzlehttp/guzzle/src/Message/Response.php:138
Stack trace:
#0 ../vendor/stage1/docker-php/src/Docker/Manager/ContainerManager.php(109): GuzzleHttp\Message\Response->json()
#1 ../vendor/stage1/docker-php/src/Docker/Manager/ContainerManager.php(163): Docker\Manager\ContainerManager->inspect(Object(Docker\Container))
#2 ../vendor/stage1/docker-php/src/Docker/Manager/ContainerManager.php(190): Docker\Manager\ContainerManager->start(Object(Docker\Container), Array)
#3 ../src/Builder.php(30): Docker\Manager\ContainerManager->run(Object(Docker\Container), NULL, Array)
#4 ../example/test.php in ../vendor/guzzlehttp/guzzle/src/Message/Response.php on line 138

The actual response is (via var_dump())

string(135) "HTTP/1.1 200 OK
Content-Type: application/json
Date: Wed, 22 Oct 2014 20:03:23 GMT
Connection: close
Transfer-Encoding: chunked

"

It looks like it is somehow related to #55 and maybe #52.

Docker Registry and Index Support

Just a question about long term vision of this library :

Does it want to support also the docker registry api and docker index api and not only the docker remote api ?

Consider upgrading dependencies to guzzle 5?

Has there been any consideration/discussion around updating docker-php's dependencies to leverage a newer release of guzzle (i.e. ~5.*)?

I'm running into a dependency conflict with another library I'd like to use, and upgrading docker-php to support the newer version of guzzle seems a more rational ask than requesting that they downgrade.

Goal to stable version

Here is a list of thing to do in order to achieve a first stable release :

Planning other apis

  • Refactoring namespace and class name to handle other apis ? #26

Docker Remote API

ContainerManager

  • List containers : GET /containers/json
  • Inspect a container : GET /containers/(id)/json
  • Create a container : POST /containers/create
  • Get logs from a container : GET /containers/{id}/logs
  • List processes runining inside a container : GET /containers/(id)/top
  • Inspect changes on a container’s filesystem : GET /containers/(id)/changes
  • Export a container : GET /containers/(id)/export
  • Start a container : POST /containers/(id)/start
  • Stop a container : POST /containers/(id)/stop
  • Restart a container : POST /containers/(id)/restart
  • Kill a container : POST /containers/(id)/kill
  • Attach to a container : POST /containers/(id)/attach
  • Wait a container : POST /containers/(id)/wait
  • Remove a container : DELETE /containers/(id)
  • Copy files or folders from a container : POST /containers/(id)/copy
  • Support WebSocket protocol for attach api (not documented in RemoteApi but available, need to see docker source code and docker-py, docker client in python, has an implementation)
  • Create a new image from a container’s changes : POST /commit
  • Create an exec process for a container : POST /containers/(id)/exec
  • Start an exec process for a container : POST /exec/(id)/start

ImageManager

  • Move api for image from Docker class to ImageManager class
  • List Images : GET /images/json
  • Create an image : POST /images/create
  • Inspect an image : GET /images/(name)/json
  • Get the history of an image : GET /images/(name)/history
  • Push an image on the registry : POST /images/(name)/push
  • Tag an image into a repository : POST /images/(name)/tag
  • Remove an image : DELETE /images/(name)
  • Search images : GET /images/search
  • Build an image from Dockerfile : POST /build

Misc

  • Check auth configuration : POST /auth
  • Display system-wide information : GET /info
  • Monitor Docker’s events : GET /events
  • Load a tarball with a set of images and tags into docker : POST /images/load
  • Show the docker version information : GET /version

Utility function

  • Simulate a docker run
  • Allow to easy remove a bunch of containers / image (clean function ?)

Guzzle 4

  • Take a decision on integration Guzzle 4 to Docker #25

ImageManager::inspect()

First, small, typo in the header
this:
* @return ImageManager
shoule be something like
* @return json data from docker inspect, $image[id] is also set

further down in that function:
$image->setId($data['Id']);
// @todo Add extra info on image
Why is the Id writteen again, and what is meant by that TODO, what extra info do you want stored? Did you also want to "re-write" the repo and tag, incase the $image variable is stale?

(I can create a pull request one it has been agreed on what to do)

following logs in realtime with logs() or attach() ?

This allows that last 20 lines of the container logs to be gathered into $logs:
$logs=$manager->logs($container, false, true, true, false, 20);

I'd like to tail the logs but stay attached and print new entries as they arrive. So tried setting the first argument $follow=true. But nothing gets printed, and it just waits.
$logs=$manager->logs($container, true, true, true, true, 20);
Also tried
$logs=$manager->logs($container, true, true, true);

Perhaps the attach() is what is needed, looking at usage.md it suggests:
$manager->attach($container)->getBody()->readWithCallBack(function($output, $type) {
print($output);
});
but that gives "Argument 2 .. must be callable"

and found this to work
$response=$manager->attach($container, function ($output, $type) {print($output);} , true);
$response->getBody()->getContents();

or:
$manager->attach($container, function ($output, $type) {print($output);} , true)->getBody()->getContents();

Then tried that in a web page, but have been unable to get realtime line by line output despite things like
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
ini_set('implicit_flush', true);
ob_implicit_flush(true);
but that is another story

So I guess my question is what is the recommended way of tailing the logs in real time (example to update in usage.md?).

About the http client

About this line : https://github.com/stage1/docker-php/blob/master/src/Docker/Http/DockerClient.php#L14

I'm not sure that it's a good place for it. It mays lead to unexpected behaviours. The library should no guess where Docker is listening. Instead the user MUST say it to the library (the endpoint param should not be optional).

Imho this line is application related and not library related. Or maybe in a special class packaged and ready to use.

Instead it could be

public function __construct( $entrypoint , array $config = [])
    {
        /* ... */
    }

But once again it will break compatibility.

Please let me know your opinion about it.

New structure proposal

Everything is available in my fork : https://github.com/SneakyBobito/docker-php but please read the following before.

Introduction

I have a proposal for a new way to implement commands in docker-php. I think that such a way would allow to make it really easyer to implement. It is also more semantic and much more clean.

It is though to be 100% extendable and rewrittable by extending classes. Then even the most complexe api endpoint that mays need complexe stuff can be implemented in this way.

Please be aware that this will break a few compatibility with previous versions.

No test has been written or updated for the moment

About the new command structure

Each command is one class. The class is named to reflect the api endpoint.

E.G POST /containers/create is available through the class Docker\Command\Post\Containers\Create

Each of these classes extend Docker\Command\AbstractCommand : https://github.com/SneakyBobito/docker-php/blob/master/src/Docker/Command/AbstractCommand.php

It offers a common way to call them for a given docker instance. $command->run($dockerInstance);

The run command returns an object that wraps the request, the response and an ouput specific to the command. If an error happens, then it returns an exception

I placed a little doccumentation about this implementation. Not sure it is very understandable at the first reading but it allows to have all in one place :
https://github.com/SneakyBobito/docker-php/blob/master/doc/internal/command.md

What did i change too

  • I added the property apiVersion to the Docker\Docker class. That allows to build such url : /v1.10/containers/create
  • I changed the constructor of Docker\Manager\ContainerManager to pass the docker instance instead of the docker client. Then it allows to call the new command structure directly from the Manager (because commands need a Docker\Docker instance, and not a http client instance)

Please if something is obscure to you feel free to ask me.

New version needed

Hello,

The commit f55f61d is a fix for a critical error. The project need to be tag as new subversion.

Please do it !

Thanks.

Compatibility with last version of Guzzle

Hello,

I did not read everything but would it be possible to integrate the latest version of Guzzle? It would make it possible to use docker-php in environments where Guzzle 6 is used.

Thanks.

Problems when get portbinds on container

When I seek information of an active container to the method $docker->getContainerManeger()->find('id'), can not access the information of ports linked to the host automatically by docker. Only returns this information by the method `$docker->getContainerManeger()->findAll() and the object is a ContainerConfig.

ContainerManager: functions should return response, not $this

Hi,

functions such as create() start() wait() stop() remove() return a ContainerManager object, but it would be more useful to return $response.
There does not seem to be much point in returning the manager and access to the response code and body can be important for flow control/debugging

restart() and kill() could also return $response

What do you think? I can create a pull request once we have agreed.

[RFC] Handling callback

Currently for build and attach api call we use callback for feedback purpose.

I'm not sure this is the best way, in fact there is 3 differents ways :

  • Keep callback
  • Use a psr0\logger interface for build and attach output
  • Use a event system (but don't think it's a good way)

I would like to hear how do you use this callback @ubermuda ? (For my part i use a psr0\logger inside)

composer refuses installation

  • Updating stage1/docker-php (dev-master 1553a73 => v0.4.0)
    Checking out cba2d26

    [RuntimeException]
    Failed to clone [email protected]:stage1/docker-php.git via git, https, ssh protocols, aborting.

    • git://github.com/stage1/docker-php.git
      error: unable to resolve reference refs/remotes/composer/fix/travis: Not
      a directory
      From git://github.com/stage1/docker-php
      ! [new branch] fix/travis -> composer/fix/travis (unable to update
      local ref)
      error: some local refs could not be updated; try running
      'git remote prune composer' to remove any old, conflicting branches

    • https://github.com/stage1/docker-php.git
      error: unable to resolve reference refs/remotes/composer/fix/travis: Not
      a directory
      From https://github.com/stage1/docker-php
      ! [new branch] fix/travis -> composer/fix/travis (unable to update
      local ref)
      error: some local refs could not be updated; try running
      'git remote prune composer' to remove any old, conflicting branches

    • [email protected]:stage1/docker-php.git
      Permission denied (publickey).
      fatal: Could not read from remote repository.

      Please make sure you have the correct access rights
      and the repository exists.

How to connect with TLS?

I can't seem to establish a connection with TLS. I have generated self-signed certificates.

I have configured my server and client as detailed below and I'm able to execute commands and manage the docker client. I have imported the CA certificate in my docker host system.

server options
--tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem -H tcp://192.168.0.11:2375 -H unix:///var/run/docker.sock

client
docker --tlsverify --tlscacert=ca.pem --tlscert=client-cert.pem --tlskey=client-key.pem -H=hostname:2375

The following code results in a stack trace and and docker log message remote error: unknown certificate authority

$client = new Docker\DockerClient([
    'remote_socket' => 'tcp://192.168.0.11:2376',
    'ssl' => true,
    'stream_context_options' => [
        'ssl' => [
            'cafile' => storage_path() . '/ssl/ca.pem',
            'local_cert' => storage_path() . '/ssl/client-cert.pem',
            'local_pk' => storage_path() . '/ssl/client-key.pem',
        ],
    ],
]);
$docker = new Docker\Docker($client);
"exception": {
    "code": 0,
    "message": "Cannot enable tls: ",
    "file": "/con/data/http/root/vendor/php-http/socket-client/src/Client.php",
    "line": 125,
    "trace": [
      {
        "file": "/con/data/http/root/vendor/php-http/socket-client/src/Client.php",
        "line": 86,
        "function": "createSocket",
        "class": "Http\Client\Socket\Client",
        "type": "->",
        "args": [
          {},
          "tcp://192.168.0.11:2376",
          true
        ]
      },
      ...
}

Relying on dev/beta packages

Hi,

With your release v0.5.0 you rely on many packages with non fixed versions. That is a big issue for projets using this. For example "jane/swagger" has no fixed version, any update on their side might brake your stuff.

Do you have any solution about that ?

How to setup volumes?

I am sorry to post this as an issue but I didn't find anything about it in documentation and former issues.

In Container class I can see we can easily manage ports, but what about volumes?

Thanks,

Thomas Decaux

(feature request) RequestException: show the contents of the connection parameter

The following line has the deliberate error of "http" instead of "tcp":
$client = new Docker\Http\DockerClient(array(), 'http://195.176.209.22:2375');
$docker = new Docker\Docker($client);
$manager = $docker->getContainerManager();
$container = $manager->find('vanilla1');
and it correctly throws an exception, see below.

./foo.php
PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'Cannot open socket connection: Unable to find the socket transport "http" - did you forget to enable it when you configured PHP? [code 0]' in /root/docker-php/vendor/stage1/docker-php/src/Docker/Http/Adapter/DockerAdapter.php:100
Stack trace:
#0 /root/docker-php/vendor/stage1/docker-php/src/Docker/Http/Adapter/DockerAdapter.php(70): Docker\Http\Adapter\DockerAdapter->createResponse(Object(GuzzleHttp\Adapter\Transaction))
#1 /root/docker-php/vendor/guzzlehttp/guzzle/src/Client.php(186): Docker\Http\Adapter\DockerAdapter->send(Object(GuzzleHttp\Adapter\Transaction))
#2 /root/docker-php/vendor/guzzlehttp/guzzle/src/Client.php(149): GuzzleHttp\Client->send(Object(GuzzleHttp\Message\Request))
#3 /root/docker-php/vendor/stage1/docker-php/src/Docker/Manager/ContainerManager.php(106): GuzzleHttp\Client->get(Array)
#4 /root/docker-php/vendor/stage1/docker-php/src/Docker/Manager/ContainerManager.php(85): Docker\Manager\ContainerManager->inspect(Ob in /root/docker-php/vendor/stage1/docker-php/src/Docker/Http/Adapter/DockerAdapter.php on line 100

Improvement suggestion: The exception does not show the contents of the connection parameter, which would be useful.

In Docker/Http/Adapter/DockerAdapter.php around line 100
if (!$socket) {
// OLD throw new RequestException(sprintf('Cannot open socket connection: %s [code %d]', $errorMsg, $errorNo), $request);
// new
throw new RequestException(sprintf('Cannot open socket connection: %s [code %d] [%s]', $errorMsg, $errorNo, $this->entrypoint), $request);
}

TLS fails in PHP 5.6

I'm running on OSX using a brew install of php 5.6

When I attempt to connect to a docker instance using TLS I was told cannot enable tls (thrown from DockerAdapter, line 107). I added some debug code and got :

RequestException in Client.php line 194:
stream_socket_enable_crypto(): Unable to locate peer certificate CN

After some digging I found this thread on SO: http://stackoverflow.com/questions/26827192/phpmailer-ssl3-get-server-certificatecertificate-verify-failed

Updating the stream context ssl settings in DockerClient.php (line 87) to the following solved the problem for me:

       $context = stream_context_create([
            'ssl' => [
                'cafile' => $cafile,
                'local_cert' => $fullcert,
                'peer_name' => $peername,
                'verify_peer_name' => false
            ],
        ]);

(Note the only change was adding 'verify_peer_name' => false)

Happy to issue a PR adding the verify_peer_name setting, although I'm on a deadline so it would be better for someone who is set up to contribute to do!

Using Docker file socket

As you said in your README :

Note: due to PHP's HTTP libraries limitations, connecting to a Docker socket is not supported. You have to use tcp. If anyone knows of an HTTP library that supports socket connections, please open a ticket, I'll be more than happy to add support for it.

You can view at Zend Http Client which use by default a Socket Adapter.
The socket adapter use the stream_socket_client method of php which is accepting all type of socket.

So with this library and by precising unix:///var/run/docker.sock it may be possible to use docker socket directly.

PS : By the way i'm very interested in your library, if you want i can do some tests with this library (but not now, more at the end of december)

Issue with JSON formatting for >5 active containers?

If I start 5 containers and call $manager->findAll() everything works fine. With >=6 I see the following error. Almost sounds like issue with Docker itself, but then again docker (which uses its own API works just fine).

PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\ParseException' with message 'Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON' in /srv/vendor/guzzlehttp/guzzle/src/Message/Response.php:137
Stack trace:                                                                                                                                                                       
#0 /srv/vendor/stage1/docker-php/src/Docker/Manager/ContainerManager.php(47): GuzzleHttp\Message\Response->json()                                                                  
#1 /srv/proxy.php(43): Docker\Manager\ContainerManager->findAll()                                                                                                                  
#2 {main}                                                                                                                                                                          
  thrown in /srv/vendor/guzzlehttp/guzzle/src/Message/Response.php on line 137

Wondering if possibly getting cut off in PHP side of things which results in JSON issue? API change?

$ docker --version
Docker version 1.2.0, build fa7b24f

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.