Create a Dockerfile with PHP + MySQL (MariaDB)

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

Here’s an example of a Dockerfile to create a web server with PHP and MariaDB:

# Define the Docker base image
FROM php:7.4-apache

# Update package repositories
RUN apt-get update

# Install necessary dependencies
RUN apt-get install -y \
    mariadb-client \
    libzip-dev \
    zip \
    unzip

# Install required PHP extensions
RUN docker-php-ext-install mysqli pdo pdo_mysql zip

# Copy the application source code to the container
COPY . /var/www/html/

# Configure Apache
COPY docker/apache2.conf /etc/apache2/apache2.conf
RUN a2enmod rewrite

# Expose port 80 to access the web server
EXPOSE 80

# Configure MariaDB
ENV MYSQL_ROOT_PASSWORD=secret
ENV MYSQL_DATABASE=mydb
ENV MYSQL_USER=myuser
ENV MYSQL_PASSWORD=mypassword

# Execute the MariaDB initialization script
COPY docker/init.sql /docker-entrypoint-initdb.d/

In this example, we create an image based on the php:7.4-apache base image. We then update the package repositories and install necessary dependencies like mariadb-client, libzip-dev, zip, and unzip. We also install required PHP extensions to run PHP applications with MySQL, including mysqli, pdo, pdo_mysql, and zip.

Next, we copy the application source code to the container and configure Apache. In this example, we copy the docker/apache2.conf file, which contains Apache configuration, to the /etc/apache2/ directory and enable the rewrite module in Apache.

Finally, we expose port 80 to access the web server and configure MariaDB. In this example, we set the environment variables MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER, and MYSQL_PASSWORD and execute the MariaDB initialization script, which we copy to the /docker-entrypoint-initdb.d/ directory.

This Dockerfile can be used to build a Docker image containing a web server with PHP and MariaDB. To build the image, you can run the following command in the same folder where the Dockerfile is located:

docker build -t myapp .

Then, you can start a container from the created image with the following command:

docker run -p 80:80 --name myapp-container -d myapp

This command starts a container in the background and names it myapp-container. The container’s port 80 is mapped to the host’s port 80, which means you can access the web server from a web browser using the host’s IP address.

I hope this example is useful to you!

Leave a Comment