Run PHP CLI Application with Docker
Docker provides official images to run PHP script on command line. These are helpful to run script on shell, scheduled jobs with php script like cron jobs. This tutorial will help you to run a sample php script on CLI using Docker containers.
Run PHP CLI on Docker
The CLI scripts run on a terminal, these scripts are helpful to background jobs, scheduled jobs with the crontab. The below example, will run a sample php script with CLI on Docker.
- Create PHP Script – First, create a sample PHP script to run on web server under the Docker container. First, switching to directory where you need to create files, then edit php script in editor:
cd ~/tutorial/ nano cli.php
Add the following content:1234<?phpecho "Welcome to tecadmin.net \n";echo "Running PHP CLI script with docker \n";?>
- Create Dockerfile – Next create a file named Dockerfile under the same directory of php script. Edit Dockerfile in your favorite text editor:
Add below content:
FROM php:7.4-cli COPY . /usr/src/myapp WORKDIR /usr/src/myapp CMD [ "php", "./cli.php" ]
Here you can choose your preferred PHP version for you Docker container. For example, to use PHP 7.1 use php:7.1-apache at the first line. Similarly use php:7.3-apache to use PHP 7.3.
- Build Docker Image – You have a Dockerfile and a index.php script in your current directory. Next, we need to create a docker image using these files. Execute below command to build and crate Docker image.
docker build -t img-php-cli-example .
You can see the newly created image by running docker images command.
- Run Container – Finally, to run your Docker container using the newly created image, type:
docker run -it --rm img-php-cli-example
You will see the results like below:
The --rm option will remove container immediately after completing execution.