How to Setup 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.

“container_name” names the container.

“image” specifies the image that docker compose should pull. “latest” signifies the latest stable image.

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

“ports” lists any ports mapped to the host from the container. WordPress uses port 80 for http so that port needs to be mapped to the host.

“volumes” lists volumes/bind mounts to mount to the container. I prefer bind mounts as they are easier to manage, and easier to backup with standard system backups.

“restart” specifies the restart policy used by the containers, and “unless-stopped” means that containers will be restarted on a restart of docker unless they were previously stopped.

“depends_on” lists other containers that will start before the container. In this instance if the database doesn’t start then WordPress won’t start.

“environment” lists environment variables that will be present in the container. In this case, the variables listed for each container mean that WordPress should automatically detect the database and set up won’t be required. An env file can also be used for lots of variables. To specify the env file this line can be added:

env_file: sample-file

To start the docker containers using docker compose, type:

docker compose up -d

The wordpress server should now be running.