Dockerizing a PHP application
Let's dive in.
Why use Docker in your PHP project?
If you are here I assume you have a basic understanding of Docker, so I will be brief. For:
consistency: replicable and predictable environment.
speed: defined and simplified processes.
isolation: from the network, file system and other processes.
How to "dockerize" a PHP application
The first step is to define our Docker image. To do this we will write a Dockerfile.
Creating a Dockerfile
All Docker images EXTEND from another image.
In case you need to take full control over the base image, you can extend FROM Docker's scratch image.
All other humans can choose between a range of pre-made images available on Dockerhub. Each of them is different and has its pros and cons.
To keep it simple, I will focus on the images based on Alpine Linux, which size is around 5MB!
This would be our Dockerfile so far:
# First we tell Docker to use an existing image in Dockerhub as a starting point
# Create a directory for our project files
RUN mkdir -p /var/www
# Copy the files in the current directory to /var/www
COPY . /var/www
# Define a starting command for the container
CMD ["php", "-S", "0.0.0.0:80", "-t", "/var/www"]
Keep in mind that the COPY command will copy all files and folders in the current directory (at the time of executing the docker build command).
We can now build our image by executing:
# Build an image, use a Dockerfile in the current directory
docker build .
# obtain the image ID from output:
# => writing image sha256:10bd10c6edc0...
This command executes one by one the lines in our Dockerfile. After each line is executed, it takes a snapshot of the system and saves it.
In case any errors arise, we can inspect the output here and correct our Dockerfile.
We can now spin up a container by executing:
# Run a container, map port 80 to 8080 at host, use image with hash 10bd10c6edc0
docker run -p 8080:80 10bd10c6edc0
# [Thu Feb 1 11:33:27 2024] PHP 8.3.2 Development Server (http://0.0.0.0:80) started
Done! We can check the result by navigating to localhost:8080.
In case you forgot to add an index file, you will see the default 404 error page: