How to reload apache in php-apache docker container via shell_exec?

I created multiple vhost and needed to reload the apache to make the vhost available, however shell_exec('service apache2 reload') didn't seem to work inside the container.

From my understanding is php-apache (link) container runs under www-data user therefore it doesn't have permission to trigger the sudo command. So is there anyway to shell_exec a sudo command.

FYI guys, this question is regarding to docker container environment not a normal Linux. Basically I can do all these commands under normal apache in the host machine, however I want to experiment it in docker container. Ultimately, I would try all the other sudo commands such as a2ensite, a2dissite, etc...

Any thought? Thanks.

2 answers

  • answered 2018-01-13 17:20 Syscall

    No, you can't to this directly, if your script is running under Apache. Your script hasn't enough rights to make such a command.

    Anyway, I think that it's a very dangerous idea to give to your script the rights to use sudo, through Apache.

    But, you can let an information in your database or a server's file. And then, let a script to reload Apache via a superuser's crontab, by example, if the information is found.

    Example code :

    <?php
    if ($something_append) {
        // let an information in the server.
        touch('/srv/have_to_reload_apache') ;
    }
    ?>
    

    The superuser's cron : (could be a sh script or whatever)

    sudo crontab -e
    

    write :

    */5 * * * * php /path/to/sudo_script.php
    

    This will run the script every 5 minutes. The script could be :

    <?php
    if (file_exists('/srv/have_to_reload_apache')) {
        shell_exec('service apache2 reload'); // Reload apache
        unlink('/srv/have_to_reload_apache'); // Remove information
    }
    ?>
    

  • answered 2018-01-13 17:36 Cryptopat

    This is very highly discouraged, regarding security.

    If you know what you are doing, usage in a locale private network, filtering user data, you can add php, or a full user as root to the sudoers file with the tool visudo.

    sudo visudo
    

    This way php won't ask for passwords at all.

    Your scripts needs then to be called with sudo, so it can contain shell_exec sudo commands

    sudo ./script.php
    

    Adding a full user is also more than highly insecured, but from my view it is also very good for dev/hack and learning. It's good to know how this works and play around , to later focus on security.

    It permit to create scratch system applications with powerful powers and their web interface.

    In the sudoers file, add:

    www-data ALL=(ALL) NOPASSWD: DNSRELOAD
    

    This is highly used in private research environment.

    See the sudoers manual: https://www.sudo.ws/man/sudoers.man.html

    A very similar question: https://unix.stackexchange.com/questions/110931/using-sudoers-to-allow-php-to-run-command