VPS Tutorials
Moodle on a VPS: complete Docker, HTTPS and recovery steps
Build a defined Moodle PHP image with PostgreSQL, Redis and private initialization. Configure HTTPS, course files, cron, SMTP and consistent backups while reviewing release support.

Moodle is an open-source learning platform for courses, training, assessment and controlled access to teaching materials. Self-hosting gives control of course files, users and plugins; operating costs move to infrastructure, maintenance and recovery rather than disappearing.
This Ubuntu 24.04/Compose guide covers PostgreSQL, Redis sessions/cache, HTTPS, cron, mail and backups. Version scope: the original Bitnami 4.5 fragment below is incomplete and is not a deployment-ready recipe. The completed alternative uses the verified Moodle 4.5.16 security-maintenance release, official PHP 8.3 Apache and PostgreSQL 16.16. Moodle 4.5 has ended general bug-fix support; review its security-support schedule and plan migration. For a new site, evaluate the currently fully supported release and its PHP/database/document-root requirements. This 4.5 layout must not be copied unchanged to newer releases with a public subdirectory. See release requirements.
| Use | CPU | RAM | Disk | Planning note |
|---|---|---|---|---|
| Personal test | 2 vCPU | 4 GB | 50 GB SSD | Few courses; avoid debug-log growth |
| Small training site | 4 vCPU | 8 GB | 100 GB NVMe | Offsite backup and deliberate Redis use |
| Multiple classes | 8 vCPU | 16 GB+ | 200 GB NVMe+ | Consider separate database/files/services |
These are estimates. Video delivery usually belongs on suitable object/video storage rather than the Moodle host. Point A/AAAA for learn.example.com at the VPS. Only administration/80/443 should be public; PostgreSQL, Redis and PHP-FPM stay private. Budget moodledata, database growth, temporary archives and recovery space. See sizing.
sudo apt update
sudo apt install -y ca-certificates curl git openssl
curl -fsSL https://get.docker.com | sudo sh
sudo usermod -aG docker "$USER"
newgrp docker
sudo mkdir -p /opt/moodle
sudo chown -R "$USER":"$USER" /opt/moodle
cd /opt/moodle
mkdir -p compose moodledata backups
touch compose/docker-compose.yml .env
chmod 600 .env
Review the privileged installer and use supported Docker. Avoid latest; record code commits, image digests and private docker compose config output. Bitnami image availability/support must be checked independently: archived images are not a source of ongoing security updates.
The completed services are moodle, postgres, redis and cron, behind host Nginx. Code stays in a versioned image; files/database use persistent volumes. This alternative is for a new installation. Migrating existing Bitnami data needs explicit paths, ownership and database compatibility checks.
The original environment is preserved for reference:
MOODLE_IMAGE=bitnami/moodle:4.5
POSTGRES_IMAGE=postgres:16
POSTGRES_DB=moodle
POSTGRES_USER=moodle
POSTGRES_PASSWORD=change-a-long-database-password
REDIS_PASSWORD=change-a-long-redis-password
MOODLE_HOST=learn.example.com
MOODLE_SITE_NAME=企业学习平台
MOODLE_ADMIN_USER=admin
MOODLE_ADMIN_PASSWORD=change-a-long-admin-password
[email protected]
openssl rand -base64 48
openssl rand -hex 32
For the completed layout, replace MOODLE_IMAGE with local/moodle:4.5.16, use distinct strong database/Redis passwords, your hostname, a localized site name and real administrator email. Initial administrator credentials are set by the CLI below, not automatically by unused image-specific variables. The new YAML explicitly selects database/cache images; the old POSTGRES_IMAGE variable alone changes nothing.
Moodle 4.5 requires PostgreSQL 13 or newer and PHP 8.1-8.3 with required extensions; the original 14+ recommendation was not a universal minimum. We use a patched PostgreSQL 16 release. Create /opt/moodle/Dockerfile with the following, pinning a reviewed PHP base digest before production:
FROM php:8.3-apache-bookworm
RUN apt-get update && apt-get install -y --no-install-recommends \
libpq-dev libicu-dev libzip-dev libpng-dev libjpeg62-turbo-dev \
libfreetype6-dev libonig-dev libxml2-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j2 pgsql intl zip gd soap mbstring opcache exif \
&& pecl install redis-6.3.0 \
&& docker-php-ext-enable redis \
&& rm -rf /var/lib/apt/lists/*
RUN printf '%s\n' 'max_input_vars=5000' 'upload_max_filesize=240M' \
'post_max_size=256M' 'memory_limit=256M' 'opcache.enable=1' \
> /usr/local/etc/php/conf.d/moodle.ini \
&& mkdir -p /var/moodledata \
&& chown www-data:www-data /var/moodledata \
&& chmod 770 /var/moodledata
COPY moodle-code/ /var/www/html/
Create /opt/moodle/config.php. It reads the server's environment and keeps moodledata outside the web document root:
<?php
unset($CFG);
global $CFG;
$CFG = new stdClass();
$CFG->dbtype = 'pgsql';
$CFG->dblibrary = 'native';
$CFG->dbhost = 'postgres';
$CFG->dbname = getenv('POSTGRES_DB');
$CFG->dbuser = getenv('POSTGRES_USER');
$CFG->dbpass = getenv('POSTGRES_PASSWORD');
$CFG->prefix = 'mdl_';
$CFG->dboptions = ['dbpersist' => false, 'dbport' => 5432, 'dbsocket' => ''];
$CFG->wwwroot = 'https://' . getenv('MOODLE_HOST');
$CFG->dataroot = '/var/moodledata';
$CFG->admin = 'admin';
$CFG->directorypermissions = 02770;
$CFG->sslproxy = true;
$CFG->session_handler_class = '\core\session\redis';
$CFG->session_redis_host = 'redis';
$CFG->session_redis_port = 6379;
$CFG->session_redis_database = 0;
$CFG->session_redis_auth = getenv('REDIS_PASSWORD');
$CFG->session_redis_prefix = 'moodle45_session:';
require_once(__DIR__ . '/lib/setup.php');
The original Compose fragment omits application database/env wiring and uses image-specific paths:
services:
postgres:
image: postgres:16
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}"]
restart: unless-stopped
volumes:
- redis_data:/data
moodle:
image: ${MOODLE_IMAGE}
restart: unless-stopped
depends_on:
- postgres
- redis
ports:
- "127.0.0.1:8080:8080"
volumes:
- moodle_data:/bitnami/moodle
- moodle_files:/bitnami/moodledata
volumes:
postgres_data:
redis_data:
moodle_data:
moodle_files:
Replace compose/docker-compose.yml with this complete alternative; do not combine the two layouts:
name: moodle45
x-moodle: &moodle
image: ${MOODLE_IMAGE:?Set a versioned local image}
build:
context: ..
env_file: ../.env
restart: unless-stopped
volumes:
- ../config.php:/var/www/html/config.php:ro
- moodle_files:/var/moodledata
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
services:
postgres:
image: postgres:16.16
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:?Define database}
POSTGRES_USER: ${POSTGRES_USER:?Define user}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Define password}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 10
redis:
image: redis:8.6.8
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:?Define password}", "--maxmemory", "256mb", "--maxmemory-policy", "noeviction"]
restart: unless-stopped
volumes:
- redis_data:/data
moodle:
<<: *moodle
ports:
- "127.0.0.1:8080:80"
cron:
<<: *moodle
user: www-data
command: ["sh", "-c", "while :; do php /var/www/html/admin/cli/cron.php; sleep 60; done"]
volumes:
postgres_data:
redis_data:
moodle_files:
The database/cache are not published. Redis holds sessions here; it is not the sole store of courses or a replacement for the PostgreSQL task system. Configure application-cache mappings separately in Moodle after testing. Size the sample Redis budget against real sessions/cache usage.
The original registry-image commands are:
docker compose -f compose/docker-compose.yml config
docker compose -f compose/docker-compose.yml pull
docker compose -f compose/docker-compose.yml up -d
docker compose -f compose/docker-compose.yml ps
For this locally built image, explicitly load .env, build the application and pull only external dependencies. Check docker compose config and inspect actual extensions:
cd /opt/moodle
git clone --depth 1 --branch v4.5.16 https://github.com/moodle/moodle.git moodle-code
git -C moodle-code rev-parse HEAD
printf '%s\n' '.env' 'backups' 'moodledata' 'moodle-code/.git' > .dockerignore
chmod 600 .env
chmod 644 config.php
docker compose --env-file .env -f compose/docker-compose.yml config --quiet
docker compose --env-file .env -f compose/docker-compose.yml build --pull moodle
docker compose --env-file .env -f compose/docker-compose.yml pull postgres redis
docker compose --env-file .env -f compose/docker-compose.yml up -d postgres redis moodle
docker compose --env-file .env -f compose/docker-compose.yml exec --user www-data moodle php -m
Keep secrets out of build context/Git. Review the verified code commit and all required extensions before initialization.
The original browser procedure accesses http://127.0.0.1:8080, selects host postgres and persists moodledata; moodledata must never be web-readable. With the completed layout, initialize privately through the CLI before opening Nginx access:
read -rsp 'Moodle administrator password: ' MOODLE_FIRST_ADMIN_PASSWORD
printf '\n'
export MOODLE_FIRST_ADMIN_PASSWORD
docker compose --env-file .env -f compose/docker-compose.yml exec -T \
--user www-data -e MOODLE_FIRST_ADMIN_PASSWORD moodle sh -c \
'php /var/www/html/admin/cli/install_database.php --agree-license \
--adminuser=admin --adminpass="$MOODLE_FIRST_ADMIN_PASSWORD" \
--adminemail="$MOODLE_ADMIN_EMAIL" --fullname="$MOODLE_SITE_NAME" --shortname=Training'
unset MOODLE_FIRST_ADMIN_PASSWORD
docker compose --env-file .env -f compose/docker-compose.yml exec --user www-data moodle \
php /var/www/html/admin/cli/cfg.php --name=wwwroot
docker compose --env-file .env -f compose/docker-compose.yml exec --user www-data moodle \
php /var/www/html/admin/cli/cron.php
docker compose --env-file .env -f compose/docker-compose.yml up -d cron
Choose a strong password without exposing it in shell history, and inspect every exit status. The original short checks are also retained:
docker compose -f compose/docker-compose.yml exec moodle php admin/cli/cfg.php --name=wwwroot
docker compose -f compose/docker-compose.yml exec moodle php admin/cli/cron.php
For the new image, use the absolute /var/www/html/admin/cli paths and run file-writing CLI tasks as www-data. Configure categories, teacher/student roles and privacy policy before course imports. Use ordinary teaching accounts; administrators, assistants and auditors receive only their required capabilities.
sudo apt install -y nginx certbot python3-certbot-nginx
sudo nano /etc/nginx/sites-available/moodle
server {
listen 80;
server_name learn.example.com;
client_max_body_size 256m;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
sudo ln -s /etc/nginx/sites-available/moodle /etc/nginx/sites-enabled/moodle
sudo nginx -t
sudo systemctl reload nginx
sudo certbot --nginx -d learn.example.com
Only the host proxy owns 80/443, with the app on private 8080. Verify trusted forwarding and Moodle's HTTPS URL, certificate renewal, login, downloads and a representative large upload. Match PHP upload_max_filesize, post_max_size and Moodle's limits to the Nginx body ceiling; allow multipart overhead. The Dockerfile's 240-MB file limit leaves room under the example's 256-MB request limit. See Caddy as an alternative gateway.
The completed cron container runs scheduled work roughly once a minute, using the same code, settings and files as web. Monitor its logs and last successful execution; long jobs need capacity checks. The original host-crontab alternative is:
* * * * * cd /opt/moodle && docker compose -f compose/docker-compose.yml exec -T moodle php admin/cli/cron.php >/dev/null 2>&1
That line belongs in crontab, not a Bash prompt. Use one scheduling method. If choosing host cron instead, stop the cron container, include the explicit env-file and absolute CLI path, run as the application user and retain useful failure logs rather than discarding all output.
Configure authenticated Redis application-cache mappings and sessions deliberately; logical database numbers do not enforce access isolation. Inspect PHP workers and slow SQL, then disk and cache. Use compatible CDN/object/video storage for heavy media, with access controls and bandwidth costs considered.
Test SMTP delivery for resets, courses, forums and assignments. SPF/DKIM/DMARC apply to the sending domain; PTR belongs to the actual sending server. Check time, TLS and provider submission/egress settings.
- Enable supported administrator MFA and use separate daily accounts.
- Limit teachers to assigned courses and auditors to read-only access.
- Disable unused registration, guest access and plugins.
- Give integrations dedicated scoped service accounts/tokens and rotate them.
- Test login-failure controls, retention and security-update notifications.
Use trusted plugins with confirmed Moodle-version compatibility. Test updates in isolation and remove abandoned dependencies deliberately.
A full copy needs PostgreSQL, code/configuration, moodledata, plugin versions and Compose. Database-only copies cannot restore submissions, attachments or avatars. The original sketch is:
mkdir -p /opt/moodle/backups
docker compose -f compose/docker-compose.yml exec -T postgres pg_dump -U "$POSTGRES_USER" "$POSTGRES_DB" | gzip > /opt/moodle/backups/moodle-$(date +%F).sql.gz
docker compose -f compose/docker-compose.yml cp moodle:/bitnami/moodledata /opt/moodle/backups/moodledata-$(date +%F)
cp .env compose/docker-compose.yml /opt/moodle/backups/
docker compose -f compose/docker-compose.yml config > /opt/moodle/backups/compose-$(date +%F).yaml
Adapt it before use: the new file path is /var/moodledata, not /bitnami/moodledata. Stop Moodle web/cron writes for a consistent database/file window, use the database container's actual user/database, strict pipeline handling, unique timestamps, protected output and gzip/hash checks. Include config.php, Dockerfile, the exact code/plugin commit, .env and actual Compose files. .env is not automatically exported to the shell; do not accept a failed dump with an empty username.
Keep encrypted offsite copies. Monthly restore drills must isolate the matching application/database versions, disable real outgoing mail/integrations and test login, courses, files, assessments and cron before removing the test environment.
- Enable maintenance and stop user/background writes.
- Save database,
moodledata, config, plugins and image identities together. - Check target PHP/database/theme/plugin requirements and rehearse in a restored copy.
- Build a separately tagged target code image and run its database upgrade during maintenance.
- Test login, courses, files, mail, cache and jobs before disabling maintenance.
docker compose -f compose/docker-compose.yml exec moodle php admin/cli/maintenance.php --enable
docker compose -f compose/docker-compose.yml pull
docker compose -f compose/docker-compose.yml up -d
docker compose -f compose/docker-compose.yml exec moodle php admin/cli/upgrade.php --non-interactive
docker compose -f compose/docker-compose.yml exec moodle php admin/cli/maintenance.php --disable
The original pull-only sequence assumes registry images; the local-image alternative needs a reviewed code checkout and image build first. Adapt CLI paths/user, and delay its final maintenance-disable command until validation succeeds. A migrated database cannot be safely downgraded merely by switching images; restore matching pre-upgrade database/files/configuration.
Check Nginx upstream private 8080, application status, PHP/database logs, memory and worker limits. Avoid raising concurrency without measuring contention.
Check client_max_body_size, upload_max_filesize, post_max_size, Moodle's limit, free space and proxy timeouts.
Inspect SMTP, DNS, egress and admin/cli/cron.php output with the correct image path/user. Check database tasks, cache and memory; do not erase pending work.
Inspect moodledata, course backups, temporary files, logs, WAL, images and older copies. Confirm offsite recovery before deleting.
- Application, PostgreSQL, Redis and web gateway work with deliberate versions.
- HTTPS, forwarding and upload limits pass real tests.
- One scheduler runs cron and Redis session/cache behavior is tested.
- SMTP, resets, notices and large uploads work.
- Administrator MFA and minimum course/audit roles are verified.
- Database,
moodledata, configuration and plugin versions are offsite. - A timed isolated restore is documented.
Start with course files, database, mail and recovery; add media offloading and automation once those work reliably.
Further reading: