Moodle Docker

  1. Moodle Docker Compose
  2. Moodle Docker Image
  3. Moodle Docker
  4. Moodle Docker Image
  5. Moodle Docker-compose

Leer en Español

  1. Joined October 26, 2015. Displaying 1 of 1 repository.
  2. In this video we'll look at how to install Moodle Learning Management System (LMS) on your Docker system.Moodle is the world's most popular learning manageme.
DockerMoodle docker swarm

It's a little bit tricky but you can use docker containers for Moodle on Windows with WSL: Install WSL. Install your Linux distribution of choice (i use ubuntu) Install Docker client for Windows. Install Docker on your WSL distribution. Enable Docker client integration with your distro (Settings Resources).

This project quickly builds a local workspace for Moodle (Apache2, PHP-FPM with XDEBUG y Postgres) using containers for each of its main components. The local workspace is built and managed by Docker Compose


  1. Install Docker. Check out how to install Docker
  2. Install Docker Compose. Check out how to install Docker Compose
  3. Download this repo: git clone https://github.com/jobcespedes/docker-compose-moodle.git && cd docker-compose-moodle
  4. Clone Moodle repo: git clone --branch MOODLE_35_STABLE --depth 1 git://github.com/moodle/moodle html
  5. Run with: docker-compose up -d


Environment variables

The following table describes environment variables set in .env. The defaults work for a initial setup. They can be modified if needed.

VariableDefault valueUse
REPO_FOLDERhtmlDefault relative path for Moodle repo
DOCUMENT_ROOT/var/www/htmlMount point inside containers for volume REPO_FOLDER
MY_TZAmerica/Costa_RicaContainers timezone
PG_LOCALEes_CRContainers locale
PG_PORT5432Postregres port to expose
POSTGRES_DBmoodlePostgres DB for Moodle
POSTGRES_USERuserDB user for Moodle
POSTGRES_PASSWORDpasswordDB password for Moodle
PHP_SOCKET9000PHP-FPM socket to connect apache2 and php-fpm services
ALIAS_DOMAINlocalhostDomain Alias
WWW_PORT80Web port to be bound
MOODLE_DATA/var/moodledataMount point inside containers for Moodle data folder
WWWROOTlocalhostHost part to set in Moodle file 'config.php' for config option 'wwwroot'

Docker Compose resources

The following table sums up Docker Compose resources.

apache2ContainerWeb serverDebian9, Apache2Apache2 server and modules for Moodle
cronContainerCron task for MoodleDebian9, CronMoodle cron task and its frequency
php-fpmContainerProcess manager for PHPDebian9, PHP-FPM, XDEBUGPHP, its modules and Moodle dependencies
postgresContainerDBMSDebian9, PostgresUser and DB
db_dumpsVolumeRestore db when builtDump files for DB to restoreTo restore an initial database if you start the container with a data directory that is empty. File name should be 'dump-init.dump'
moodledataVolumeMoodle data storeData generated by moodleMoodle data dir
REPO_FOLDERVolumeMoodle codeMoodle codeIt is set to 'html/' by deafult (check out .env)

Project management with Docker Compose

Inside project folder

Moodle Docker Compose

  1. Run project
  2. Stop project
  3. Start project
  4. Remove project
  5. Logs


Use idekey PHPTEST


Debug config for IDE PHPStorm:

Moodle Docker
  1. Add server:
    • Settings -> Languages -> PHP -> Servers
    • Name: localhost
    • Host: localhost
    • Port: 80
    • Debugger: Xdebug
    • Use path mapping: checked
    • Absolute path on the server: /var/www/html
  1. Add PHP remote debug
    • Run / Debug Configurations -> PHP remote debug
    • Use server created in step #1 and set idekey PHPTEST
  1. Enable Start listening for PHP Debug Connections

Cron debugging

Follow previous steps, set a breakpoint and then run:

There is a scrip for Specific cron tasks. For example:


Config pgadmin4

  1. Go to http://localhost:5050
  2. In File -> Preferences -> Binary paths set /usr/bin
  3. Add new server:
    • Tab General
      • Name: Any name you want
    • Tab Connection
      • Host name/address: postgres
      • Host Username: user
      • Host Password: password
    • Save

Backup and restore database

When needed, backup and restore of the database could be done in the following way.

A database can be automatically restored when postgres service starts. By placing a dump file inside 'db_dumps' folder and naming it 'dump-init.dump', postgres container will try to restore that file as an initial database if data directory is empty.

IMPORTANT: Depending of size, database initial availability could be delayed

Este es un repositorio para crear rápidamente un entorno de trabajo con Moodle (Apache2, PHP-FPM con XDEBUG y Postgres) usando contenedores para cada uno sus principales componentes. El entorno de trabajo se crea y gestiona con Docker Compose.

Pasos rápidos para crear proyecto:

  1. Tener Docker. Ver como instalar Docker
  2. Tener Docker Compose. Ver como instalar Docker Compose
  3. Descargar este repo y acceder a él: git clone https://github.com/jobcespedes/docker-compose-moodle.git && cd docker-compose-moodle
  4. Copiar repositorio de código de Moodle: git clone --branch MOODLE_35_STABLE --depth 1 git://github.com/moodle/moodle html
  5. Desplegar con: docker-compose up -d

Variables de ambiente

La siguiente tabla contiene las variables utilizadas en el archivo .env para Docker Compose. Los valores por defecto funcionan para una configuración inicial. Cámbielos de ser necesario.

VariableValor por defectoUtilidad
REPO_FOLDERhtmlRuta relativa para el código de Moodle
DOCUMENT_ROOT/var/www/htmlPunto de montaje para REPO_FOLDER dentro de contenedores
MY_TZAmerica/Costa_RicaZona horaria para los contenedores
PG_LOCALEes_CRConfiguración de lugar
PG_PORT5432Puerto de base de datos postgres a publicar
POSTGRES_DBmoodleNombre de la base de datos postgres de Moodle
POSTGRES_USERuserNombre de usuario de la base de datos postgres de Moodle
POSTGRES_PASSWORDpasswordContraseña de la base de datos postgres de Moodle
PHP_SOCKET9000Socket para conectar apache2 con php-fpm
ALIAS_DOMAINlocalhostAlias del Dominio
WWW_PORT80Puerto web a publicar
MOODLE_DATA/var/moodledataCarpeta de datos de Moodle a montar en los contenedores
WWWROOTlocalhostPara de nombre de host en la url de config.php de Moodle

Estructura de Docker Compose

A continuación se incluye una tabla que resume la estructura del archivo de Docker Compose:

apache2ContenedorServidor webDebian9, Apache2El mínimo de módulos de Apache2
cronContenedorTarea de cron de MoodleDebian9, CronFrecuencia de ejecución de tarea cron de Moodle
php-fpmContenedorInterprete y manejador de procesos para PHPDebian9, PHP-FPM, XDEBUGModulos de php y paquetes adicionales para Moodle
postgresContenedorGestor de base de datosDebian9, PostgresUsuario y base de datos
db_dumpsVolumenRestaurar una base de datos inicialArchivos de respaldo de base de datos.Para restaurar al iniciar si se comienza con directorio de datos vacío. El nombre del archivo de respaldo a utilizar debe ser 'dump-init.dump'
moodledataVolumenAlmacén de datos de MoodleArchivos generados por MoodleMoodle data dir
REPO_FOLDERVolumenCódigo de aplicaciónCódigo de MoodlePor defecto es './html' (ver archivo .env)

Gestión del proyecto con Docker Compose

Dentro de la carpeta del proyecto

  1. Correr proyecto
  2. Detener el proyecto
  3. Iniciar el proyecto
  4. Eliminar proyecto
  5. Logs


Se utiliza el idekey PHPTEST


Configuración para depurar con IDE PHPStorm:

  1. Agregar server:
    • Settings -> Languages -> PHP -> Servers
    • Name: localhost
    • Host: localhost
    • Port: 80
    • Debugger: Xdebug
    • Use path mapping: checked
    • Absolute path on the server: /var/www/html
  1. Agregar PHP remote debug
    • Run / Debug Configurations -> PHP remote debug
    • Use server created in step #1 and set idekey PHPTEST
  1. Activar botón Start listening for PHP Debug Connections

Depurar tareas de cron

Siga los pasos anteriores, establezca una interrupción y ejecuta en el la línea de comandos:

Se pueden ejecutar también tareas específicas de cronPor ejemplo:


Pasos para usar pgadmin4

  1. Ingresar a http://localhost:5050
  2. En File -> Preferences -> Binary paths establecer en /usr/bin
  3. Agregar nuevo servidor:
    • Pestaña General
      • Name: Un nombre para el servidor
    • Pestaña Connection
      • Host name/address: postgres
      • Host Username: user
      • Host Password: password
    • Guardar

Respaldar y restaurar la base de datos

Es posible respaldar y restaurar la base de datos de la siguiente manera.

Se puede restaurar una base de datos, usando pg_dump (formato personalizado de Posgres), a la caperta 'db_dumps' y nombrando el archivo como dump-init.dump

IMPORTANTE: Dependiendo del tamaño, la ejecución de este sql podría demorar la disponibilidad inicial de la base de datos.

Acceptance Testing (Behat) with Docker

Moodle Docker

As a Moodle plugin developer, particularly if you intend to release your plugin via the directory, you will want to test your code in different scenarios. Typically I find that clients want a plugin for the current version of Moodle they are running but there always seems to be plans afoot to upgrade to a newer version and your plugin is expected to work in that version too. I like to develop with MySQL tables but occasionally the client runs a different database engine. To manage such diversity when testing, you may want to consider using the docker containers provided by Moodle HQ at in their git repository at https://github.com/moodlehq/moodle-docker. I, for one, wish I had discovered this previously.

A good question to ask yourself before attempting to create automated unit and accaptance tests for your plugin development project is whether it is worth the effort and whether your client is likely to accept the additional cost of doing so. I delve into these questions in another article but if you find yourself having to generate and test automated tests or manual testing in different scenarios, the docker solution is a good choice.

If you do not know what docker is, here is one definition “ Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package.” The Moodle docker environment is not actually a container but uses docker Compose to configure several docker containers to provide a Moodle environment and you get to provide the Moodle code to test.

As far as I can make out, it is possible to run Docker containers in Windows, if you must, so be aware that this article is Linux biased. For more information about using Linux containers on Windows see https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/linux-containers.

To see the different scenarios that you can test your plugin code with, consider the environment variables that you can set for the tests.

Environment Variable


Possible values

Default value



pgsql, mariadb, mysql, mssql, oracle




7.3, 7.2, 7.1, 7.0, 5.6




firefox, chrome


Using git to manage your Moodle installation (see https://docs.moodle.org/37/en/Git_for_Administrators), you can more easily test several versions of Moodle with your plugin installed. The local repository directory can be your local webserver’s Moodle document root. The webserver by default runs on localhost and port 8000 though along with the document root, you can set the values as you see fit using the relevant environment settings.

Environment Variable


Possible values

Default value



any valid hostname




any integer value




path on your file system


There are a few more environment variables – full list is available at https://github.com/moodlehq/moodle-docker.

To get started, you will need to install docker community edition. The instructions are at https://docs.docker.com/install/ and I found it fairly straightforward to install docker onto my Ubuntu laptop. After that you need to install the Compose tool and follow the relevant instructions at https://docs.docker.com/compose/install/.

Follow this up by cloning the Moodle docker repository – or alternatively download and unzip the repository - onto your device.

Now to run the Moodle environment, you need to set the required environment variables MOODLE_DOCKER_DB and MOODLE_DOCKER_WWWROOT and then copy the docker config file ‘config.docker-template.php’ to the wwwroot folder as config.php. I typically have this set up as a shell script but if you are a Linux user, you will need to use the source command (or the extra .) so that the script runs in your current environment otherwise the enviromental variables are lost when the script completes.

So typically, in the moodle docker folder, you would:

  1. Set MOODLE_DOCKER_WWWROOT=/path/to/moodle/repository

  2. Set MOODLE_DOCKER_DB=pgsql mariadb mysql mssql oracle

  3. Copy config.docker-template.php $MOODLE_DOCKER_WWWROOT/config.php

  4. Start up the containers with ‘ bin/moodle-docker-compose up -d’, the -d means detach i.e. runs in the background.

  5. Wait for DB to come up (important for oracle/mssql) with ‘ bin/moodle-docker-wait-for-db

Even if I am planning to just run automated tests, I still like to setup so I can log into the Moodle instance so I can install and uninstall my plugin code and for manual testing:

  1. Run bin/moodle-docker-compose exec webserver php admin/cli/install_database.php --agree-license --fullname='Docker moodle' --shortname='docker_moodle' --adminpass='Pa55w0rd' --adminemail='[email protected]'

Moodle Docker Image

It is likely that you may not complete all your tests for each environment so sometimes you want to keep the data etc for the next time. For those occasions, you need to stop the containers and keep their state. This is achieved by running ‘ bin/moodle-docker-compose stop’ and then ‘ bin/moodle-docker-compose start’ in the Moodle docker folder to restart. You do have to setup the enviroment variables for the restart. To destroy the environment, you need to run ‘ bin/moodle-docker-composedown’.

Moodle Docker

Before starting the Moodle docker environment, I would typically checkout the Moodle version I want to test against. I normally install the plugin after the core Moodle is up and running so I can test the installation and before tearing it all done, the uninstall. Alternatively, you could copy your plugin’s folder into the Moodle repository folder prior to starting the docker containers. In the default setup, Moodle will be running on http://localhost:8000/.

Using git for Moodle gives you various options when testing. You can test new installations of your plugin on different Moodle versions as well as test upgrades from one version to the another. Obviously you can test with different database engines as well as with different versions of PHP.

Moodle Docker Image

The Moodle docker provides a way to run the Moodle CLI (command line interface) scripts with the ‘ bin/moodle-docker-compose exec webserver’ command option. So in order to initialise your test enviroments you would typically run ‘ bin/moodle-docker-compose exec webserver php admin/tool/phpunit/cli/init.php’ for PHPUnit tests and bin/moodle-docker-compose exec webserverphp admin/tool/behat/cli/init.php for Behat acceptance testing. The Behat faildump directory is exposed at http://localhost:8000/_/faildumps/. You can also watch – at least the javascript tests – by installing and using a Virtual Network Computing (VNC) session – see https://github.com/moodlehq/moodle-docker#using-vnc-to-view-behat-tests for more information.

To run tests, refer to the documentation of the Moodle site. For Behat tests, see https://docs.moodle.org/dev/Running_acceptance_test#Step_2:_Running_acceptance_test_environment and https://docs.moodle.org/dev/PHPUnit#Test_execution for PHP unit tests.

The command to run the behat tests is slightly different from the the usual ‘ vendor/bin/behat --config /path/to/your/CFG_behat_dataroot/behatrun/behat/behat.yml --tags mod_myplugin’

instead being ‘ bin/moodle-docker-compose exec webserverphp admin/tool/behat/cli/run.php –[email protected]_manual’.

Emails generated by the Moodle instance are captured by Mailhog and you can view them in the ‘ /_/mail’ folder.

The Moodle docker environment consists of a number of docker containers :

  • moodle-docker_webserver_1

  • moodle-docker_mailhog_1

  • moodle-docker_exttests_1

  • moodle-docker_selenium_1

  • moodle-docker_db_1

If you need access to the container which are mainly Linux based – for example, to get access to the database, you can do so by running ‘ docker exec -it $container$ /bin/bash’.

This article is one in a series covering automated testing for Moodle plugin development. You can find the other articles on the site.

Moodle Docker-compose

  • Most Viewed News

    • Wsl2 Install Docker
    • Google Play App Download Mac
    • Mac Split Screen App Free
    • R Studio Download Mac Os