Search code examples
phpdockerpermissionsexecpermission-denied

Docker PHP exec() function: permission denied


I'm trying to run the exec() function in PHP, but I'm getting a 'Permission denied' output. PHP is installed as a Docker container. I'm getting this on Raspberry PI as well as on my Macbook.

For a test, I installed LAMP without Docker, and it works fine, but on Docker it doesn't.

For example, when I run

echo exec('docker --version');

I'm getting this info in my PHP script in the browser:

sh: 1: docker: Permission denied

And it doesn't matter whether I run exec() function or any alternative like shell_exec() or system(). I've been trying everything with no success for the last few days. This must be a docker thing, but I have no idea what it is.

Some things that I tried:

  • changed ownership of my .PHP file and dirs where it is located
  • changed permissions to 777
  • added www-data user to sudoers file
  • added www-data to docker group

Solution

  • The error you're getting indicates the exec is working, but the user that is running the command doesn't have access to the docker binary.

    You'll have to modify the permissions inside the docker container to allow the web user to run the docker command. You will want to add those steps to your Dockerfile.

    RUN chmod go+x `which docker`
    

    Should allow any user to run the docker command inside the container, but may be considered a security risk.


    Note that in the command above, I was thinking you would copy and paste the command directly. The which command will locate the docker executable, and the backticks that enclose which docker will use the output in the chmod command, making it unnecessary to know the exact location for the docker executable.