Run PHP Web Application with Docker
You can run any PHP application on using web server or command line using Docker containers. This tutorial will help you to run a PHP script over command line with a Docker container. Also, you will find the instructions to run a PHP script over Apache/Nginx web server with Docker.
Docker PHP Example with Apache
- Create PHP Script – First, create a sample PHP script to run on web server under the Docker container. Edit index.php in your favorite text editor.
Add the following content:PHP1234<?phpecho "Welcome to tecadmin.net </br>";echo "Running PHP with Apache on Docker";?>
Save file and close.
- Create Dockerfile – Next create a file named Dockerfile under the same directory. Edit Dockerfile in a text editor:
Add below content to file.
FROM php:7.4-apache COPY . /var/www/html
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 Image – You have a Dockerfile and a sample index.php script in your current directory. Now, you need to create a docker image with these files. Execute below command to build and crate Docker image.
docker build -t img-php-apache-example .
The above command will create a Docker image with name img-php-apache-example. Use “docker images” command to list available images on local system.
- Run Container –Now, you have a docker image now. Use this docker image to launch a new container on your system. To run your Docker container using the newly created image, type:
docker run -it img-php-apache-example
Bind a port from docker host to container’s port. The below command will map port 8089 of host machine to port 80 of the container.
docker run -it -d -p 8080:80 img-php-apache-example
The “-d” option detach the container from current shell and run in background. This will print container ID on screen.
- Access Application – Once the container is in running state. All the requests to host machine on port 8080 will routed to docker container’s port 80.
Access you docker host using IP address (or hostname/domain name) on port 8080 to view application.