How to set up a PHP environment in Docker?

To set up a PHP environment in Docker, you can follow these steps:

  1. Install Docker: Before we begin, make sure you have Docker installed and the Docker service is up and running.
  2. Create a Dockerfile: In the project’s root directory, create a file called Dockerfile and input the following content:
FROM php:latest

This Dockerfile is built on top of the latest version of the PHP image.

  1. Build Docker image: Navigate to the project’s root directory in the terminal, and run the following command to build the Docker image:
docker build -t php-env .

One of them is the name of the image, php-env, which can be modified as needed.

  1. Start Docker container: Run the following command to initiate the Docker container:
docker run -d --name php-container -v /your/project/path:/var/www/html -p 8080:80 php-env

In this case, “/your/project/path” is the path of your local project, which can be modified according to your actual situation; 8080 is the local port number, which can be modified as needed.

  1. Accessing a container: If you need to execute commands inside a container, you can do so by using the following command:
docker exec -it php-container bash

This way, you can carry out various PHP-related operations inside the container.

You have successfully set up a PHP environment and run it in Docker. You can access your PHP application by visiting http://localhost:8080.

bannerAds