A Dockerfile is a text-based file used to create Docker containers. It defines how to build and configure a container image for an application, specifying the steps to be taken.
The Dockerfile allows you to define dependencies, plugins, environment variables, and commands to be executed in sequence for your application.
A container can be run in three steps using a Dockerfile:
- Create the Dockerfile.
- Build the Docker Image with the prepared Dockerfile.
- Run the Docker Container by executing the Docker Image.
For example, let’s create a Docker Image for a simple PHP environment using a Dockerfile:
# Use the official PHP image FROM php:8.2-apache # Install necessary PHP extensions RUN docker-php-ext-install mysqli pdo pdo_mysql # Enable Apache RUN a2enmod rewrite # Set the working directory WORKDIR /var/www/html # Copy the project code into the container COPY . /var/www/html
To build the container image with the prepared Dockerfile, run the following command in the directory where the Dockerfile is located:
docker build -t my_php_image .
We have created a container image named “my_php_image.” You can list all created images with the following command:
To start a container named “my_php_container” from the Docker Image we created, use the following command:
docker run -d -p 8080:80 --name my_php_container my_php_image
You can view the index.php file by visiting http://localhost:8080/ in your browser. Note that we redirected the default Apache port (80) to port 8080 with Port Mapping.
Development Inside the Docker Container (Mount Volumes)
To enable live code reloading and keep your changes visible inside the container, you can mount a local directory to the container using the following command:
docker run -d -p 8080:80 -v .:/var/www/html --name my_php_container my_php_image
Once your development work is finished, you can stop and remove the container:
docker stop my_php_container docker rm my_php_container
If you no longer need it, you can also remove the Docker Image:
docker rmi my_php_image