How to Set Up WordPress in Docker

For this tutorial I will be using docker compose.

Here is my docker- compose.yml file:

version: "3.8"   
services:
    db:
        container_name: db
        image: mariadb:latest
        user: 1000:1000
        volumes:
            - /server/data/website/database:/var/lib/mysql
        environment:
            - MYSQL_ROOT_PASSWORD=password
            - MYSQL_DATABASE=db_name
            - MYSQL_USER=user
            - MYSQL_PASSWORD=password
        restart: unless-stopped

    wordpress:
        container_name: wordpress
        image: wordpress:latest
        ports: "80:80"
        volumes:
            - /server/data/website/website:/var/www/html
        environment:
            - WORDPRESS_DB_HOST=db
            - WORDPRESS_DB_USER=user
            - WORDPRESS_DB_PASSWORD=password
            - WORDPRESS_DB_NAME=db_name
        restart: unless-stopped
        depends_on:
            - db

I have chosen to use MariaDB over MySQL because it is generally faster, but you can use any docker based SQL RDBMS.

I use “user: 1000:1000” for the database so that files created on my bind mount are owned by my user. Otherwise the files were owned by user 931.

WordPress uses port 80 for http so I’ve mapped that port to the host machine.

The WordPress container “depends_on” the database. If the database doesn’t run then WordPress doesn’t either. This is necessary as WordPress requires a database to work.

The environment variables for the database are required to initialise it. MYSQL_ROOT_PASSWORD specifies the password for the root MYSQL account. MYSQL_DATABASE specifies the name for a database to be created on startup of the container. MYSQL_USER and MYSQL_PASSWORD must be created together. They create a MySQL user that is given superuser permission to the database defined by MYSQL_DATABASE.

The environment variables for WordPress are not necessary. The container can be started without them, but it will need to be manually connected to the database. It is recommended to include the variables to simplify the installation. WORDPRESS_DB_HOST specifies the container name of the RDBMS. WORDPRESS_DB_USER and WORDPRESS_DB_PASSWORD specify the username and password created in the database environment variables. WORDPRESS_DB_NAME specifies the name of the database.

To start the docker containers using docker compose, type:

docker compose up -d

WordPress should now be running connected to the database.