Shurn the Awesomer
Controlling Docker Containers with PHP

Controlling Docker Containers with PHP

Written on Fri, 6 January 2017

After searching through the internet to find out how to manage docker containers through PHP, I finally figured out how to do it. I assume you are using Ubuntu 16.04 and the docker you are using is the latest to date.

Add www-data to docker

According to the documentation, the docker daemon always runs as the root user. Since Docker version 0.5.2, the docker daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user root, and so, by default, you can access it with sudo.

Starting in version 0.5.3, if you (or your Docker installer) create a Unix group called docker and add users to it, then the docker daemon will make the ownership of the Unix socket read/writable by the docker group when the daemon starts. The docker daemon must always run as the root user, but if you run the docker client as a user in the docker group then you don't need to add sudo to all the client commands.

So we are going to add www-data to docker so that it can run docker commands. First, let's create the group if it doesn't exist. Skip this command if the group exists.

sudo groupadd docker

Add www-data to docker group.

sudo gpasswd -a www-data docker

Reboot the computer for all the permissions to take effect.

sudo reboot

Writing docker commands

In PHP, you will need to specify the commands in this syntax:

shell_exec("RET=`docker command `;echo $RET');

For example, if you want to run hello world, you write this:

shell_exec('RET=`docker run hello-world`;echo $RET');