mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Docker Compose for VPS (Let's Encrypt, MariaDB) and intranet (internal CA, SQLite): images, setup script, backups, real-stack test; relative redirects in nginx snippet
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
.git
|
||||
.local
|
||||
.venv*
|
||||
node_modules
|
||||
dist
|
||||
vendor
|
||||
site
|
||||
tests
|
||||
docs
|
||||
backend/db.sqlite3
|
||||
backend/staticfiles
|
||||
**/__pycache__
|
||||
*.pyc
|
||||
docker/.env*
|
||||
docker/backups
|
||||
@@ -38,3 +38,4 @@ build/
|
||||
!.vscode/extensions.json
|
||||
.DS_Store
|
||||
.local/
|
||||
docker/backups/
|
||||
|
||||
@@ -69,6 +69,7 @@ passe dans `/etc/pyquest/env`) → `systemctl enable --now pyquest` → `./scrip
|
||||
| `scripts/server_manage.sh` | `manage.py` de production (lit `/etc/pyquest/env` sans `source`) | faux Python |
|
||||
| `scripts/vps_doctor.sh` | diagnostic en lecture seule (reconnaît l'installation intranet) | exécution locale |
|
||||
| `deploy/install_vps.sh` | installateur VPS tout-en-un : contrôles, server_setup, MariaDB, service, admin, publication, cron | `--dry-run` + `tests/deploy/test_intranet.sh` |
|
||||
| `docker/setup.sh vps|intranet` + `docker/compose.{vps,intranet}.yaml` + `docker/Dockerfile` | variante Docker : images web (nginx + site construit dans l'image) et backend, certbot (VPS) ou autorité interne (intranet), sauvegardes ; secrets dans `docker/.env.<mode>` | `make test-docker` : piles réelles (hors Let's Encrypt réel) |
|
||||
| `deploy/install_intranet.sh` | installateur réseau interne (lycée) : autorité de certification interne (`scripts/intranet_cert.sh`), SQLite (`PYQUEST_DB_ENGINE=sqlite`), vhost `nginx/pyquest-intranet.conf.example`, page `/ca` (`deploy/intranet-ca.html`), cron certificat mensuel + sauvegarde | vrai openssl et vrai nginx (`tests/deploy/test_intranet.sh`) ; **jamais lancé sur un vrai serveur**. Décision utilisateur : postes partagés → un profil de navigateur (idéalement une session) par élève, voir docs host/installers |
|
||||
| `scripts/backup_db.sh` | sauvegarde MariaDB vérifiée + rotation | faux `mariadb-dump` |
|
||||
| `scripts/check_deploy.sh URL` | contrôle du site publié | serveur local et vrai nginx (`make dev-nginx`) |
|
||||
|
||||
@@ -5,7 +5,7 @@ VENV := .venv
|
||||
VENV_PY := $(VENV)/bin/python
|
||||
PORT ?= 8000
|
||||
|
||||
.PHONY: help install vendor-pyodide dev validate-levels build dev-sync fetch-nginx dev-nginx dev-admin dev-author docs docs-serve vps-doctor check-deploy test-deploy test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean
|
||||
.PHONY: help install vendor-pyodide dev validate-levels build dev-sync fetch-nginx dev-nginx dev-admin dev-author docs docs-serve vps-doctor check-deploy test-deploy test-docker test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean
|
||||
|
||||
help: ## Affiche cette aide
|
||||
@grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}'
|
||||
@@ -39,6 +39,9 @@ test-deploy: ## Teste les scripts d'installation (VPS, intranet) et d'exploitati
|
||||
bash tests/deploy/test_server_scripts.sh
|
||||
bash tests/deploy/test_intranet.sh
|
||||
|
||||
test-docker: ## Essai réel des compose Docker (intranet et VPS) : construit, démarre, interroge, détruit (quelques minutes)
|
||||
bash tests/deploy/test_docker.sh
|
||||
|
||||
DOCS_VENV := .venv-docs
|
||||
|
||||
$(DOCS_VENV)/.installed: requirements-docs.txt
|
||||
|
||||
@@ -68,6 +68,8 @@ Tested scripts for installation, atomic-release deployment, diagnostics and back
|
||||
One-command installation: `./deploy/install_vps.sh --domain …` (public VPS, Let's Encrypt, MariaDB) or
|
||||
`./deploy/install_intranet.sh --host …` (school network: internal certificate authority, SQLite), see
|
||||
[docs/site/en/host/installers.md](docs/site/en/host/installers.md).
|
||||
With Docker: `./docker/setup.sh vps --domain …` or `./docker/setup.sh intranet --host …`
|
||||
(ready-to-use compose files, see [docs/site/en/host/docker.md](docs/site/en/host/docker.md)).
|
||||
Production-faithful local test: `make dev-nginx`.
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -68,6 +68,8 @@ Scripts testés d'installation, de mise à jour par versions atomiques, de diagn
|
||||
Installation en une commande : `./deploy/install_vps.sh --domain …` (VPS public, Let's Encrypt, MariaDB) ou
|
||||
`./deploy/install_intranet.sh --host …` (réseau de lycée : autorité de certification interne, SQLite), voir
|
||||
[docs/site/fr/host/installers.md](docs/site/fr/host/installers.md).
|
||||
Avec Docker : `./docker/setup.sh vps --domain …` ou `./docker/setup.sh intranet --host …`
|
||||
(compose prêts à l'emploi, voir [docs/site/fr/host/docker.md](docs/site/fr/host/docker.md)).
|
||||
Essai local fidèle à la production : `make dev-nginx`.
|
||||
|
||||
## Contribuer
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Images PyQuest : « web » (nginx + site statique) et « backend » (Django + gunicorn).
|
||||
# Contexte de construction : la racine du dépôt (voir docker/compose.*.yaml).
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ---- Site statique : moteur Python (Pyodide, version épinglée et vérifiée) puis construction de dist/ -------------------
|
||||
FROM python:3.12-slim-bookworm AS site
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends curl bzip2 ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /src
|
||||
COPY scripts/vendor_pyodide.sh scripts/
|
||||
RUN ./scripts/vendor_pyodide.sh
|
||||
COPY app app
|
||||
COPY levels levels
|
||||
COPY scripts/build.py scripts/
|
||||
RUN python scripts/build.py
|
||||
|
||||
# ---- Serveur web : nginx (>= 1.25.1 pour http2 on) ---------------------------------------------------------------------
|
||||
FROM nginx:1.27-alpine AS web
|
||||
RUN apk add --no-cache bash openssl
|
||||
RUN rm -f /etc/nginx/conf.d/default.conf && mkdir -p /etc/nginx/snippets /etc/nginx/tls /opt/pyquest/nginx /var/www/pyquest/ca /var/www/pyquest/static
|
||||
# Mêmes extraits que sur un serveur classique ; seul le relais vers Django change (service « backend », adresse
|
||||
# résolue à l'exécution par le DNS de Docker : un backend recréé n'oblige pas à redémarrer nginx).
|
||||
COPY nginx/pyquest-locations.conf.example /tmp/locations.conf
|
||||
RUN sed -e 's#proxy_pass http://127.0.0.1:8001#proxy_pass http://$pq_upstream#' /tmp/locations.conf > /etc/nginx/snippets/pyquest-locations.conf \
|
||||
&& rm /tmp/locations.conf \
|
||||
&& grep -q 'pq_upstream' /etc/nginx/snippets/pyquest-locations.conf
|
||||
COPY nginx/pyquest-author-headers.conf.example /etc/nginx/snippets/pyquest-author-headers.conf
|
||||
COPY nginx/pyquest.conf.example nginx/pyquest-intranet.conf.example /opt/pyquest/nginx/
|
||||
COPY deploy/intranet-ca.html /opt/pyquest/intranet-ca.html
|
||||
COPY scripts/intranet_cert.sh /usr/local/bin/intranet_cert.sh
|
||||
COPY docker/web/pyquest-tls /usr/local/bin/pyquest-tls
|
||||
COPY docker/web/40-pyquest.sh /docker-entrypoint.d/40-pyquest.sh
|
||||
RUN chmod 755 /usr/local/bin/intranet_cert.sh /usr/local/bin/pyquest-tls /docker-entrypoint.d/40-pyquest.sh
|
||||
COPY --from=site /src/dist /var/www/pyquest/current
|
||||
EXPOSE 80 443
|
||||
|
||||
# ---- Backend : les roues (dont mysqlclient, à compiler) sont construites à part ---------------------------------------
|
||||
FROM python:3.12-slim-bookworm AS backend-wheels
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends build-essential pkg-config libmariadb-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY backend/requirements.txt backend/requirements-server.txt backend/requirements-prod.txt /req/
|
||||
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r /req/requirements-prod.txt
|
||||
|
||||
FROM python:3.12-slim-bookworm AS backend
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libmariadb3 \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& groupadd --system --gid 10001 pyquest \
|
||||
&& useradd --system --uid 10001 --gid pyquest --no-create-home --shell /usr/sbin/nologin pyquest \
|
||||
&& mkdir -p /var/www/pyquest/static /var/lib/pyquest \
|
||||
&& chown pyquest:pyquest /var/www/pyquest/static /var/lib/pyquest
|
||||
COPY --from=backend-wheels /wheels /wheels
|
||||
COPY backend/requirements.txt backend/requirements-server.txt backend/requirements-prod.txt /req/
|
||||
RUN pip install --no-cache-dir --no-index --find-links /wheels -r /req/requirements-prod.txt && rm -rf /wheels /req
|
||||
COPY backend /app/backend
|
||||
COPY docker/backend/entrypoint.sh docker/backend/healthcheck.py /app/
|
||||
RUN chmod 755 /app/entrypoint.sh
|
||||
WORKDIR /app/backend
|
||||
ENV DJANGO_SETTINGS_MODULE=pyquest_api.settings.production PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
# Pas de USER : l'entrée démarre en root pour donner les volumes à pyquest, puis abandonne ses droits (setpriv).
|
||||
EXPOSE 8000
|
||||
HEALTHCHECK --interval=15s --timeout=5s --start-period=40s --retries=5 CMD ["python", "/app/healthcheck.py"]
|
||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Démarrage du backend : migrations, fichiers statiques de l'administration (volume partagé avec nginx), puis gunicorn.
|
||||
set -e
|
||||
cd /app/backend
|
||||
# Les volumes nommés sont créés avec le propriétaire du premier conteneur qui les monte (nginx, en root) : on les rend
|
||||
# à l'utilisateur sans privilèges, sous lequel tourne ensuite tout le reste.
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
chown pyquest:pyquest /var/www/pyquest/static /var/lib/pyquest
|
||||
exec setpriv --reuid=10001 --regid=10001 --clear-groups "$0" "$@"
|
||||
fi
|
||||
python manage.py migrate --noinput
|
||||
python manage.py collectstatic --noinput --verbosity 0
|
||||
exec gunicorn pyquest_api.wsgi --bind 0.0.0.0:8000 --workers "${PYQUEST_WORKERS:-3}" --access-logfile - --error-logfile -
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Sonde de santé : le contrôle d'accès de l'éditeur répond 401 sans session (Django et ses réglages sont donc chargés)."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
host = os.environ.get("PYQUEST_ALLOWED_HOSTS", "localhost").split(",")[0]
|
||||
# Django n'accepte que les noms autorisés et exige l'en-tête du proxy pour ne pas rediriger vers HTTPS.
|
||||
request = urllib.request.Request(
|
||||
"http://127.0.0.1:8000/api/auth/check/",
|
||||
headers={"Host": host, "X-Forwarded-Proto": "https"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=4)
|
||||
except urllib.error.HTTPError as error:
|
||||
sys.exit(0 if error.code == 401 else 1)
|
||||
except OSError:
|
||||
sys.exit(1)
|
||||
sys.exit(1)
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
# Sauvegarde quotidienne de la base MariaDB (conteneur « backup » du compose VPS). Le mot de passe vient de MYSQL_PWD.
|
||||
# Une sauvegarde est écrite dans un fichier provisoire puis déplacée : une sauvegarde ratée ne remplace jamais une bonne.
|
||||
set -eu
|
||||
KEEP="${PYQUEST_BACKUP_KEEP:-14}"
|
||||
umask 077
|
||||
while :; do
|
||||
file="/backups/pyquest-$(date +%Y%m%d-%H%M%S).sql.gz"
|
||||
if mariadb-dump -h db -u "${MARIADB_USER}" --single-transaction --routines --default-character-set=utf8mb4 "${MARIADB_DATABASE}" | gzip -9 > "${file}.part" \
|
||||
&& [ "$(gunzip -c "${file}.part" | wc -c)" -gt 500 ]; then
|
||||
mv "${file}.part" "${file}"
|
||||
# Propriétaire du dossier monté (l'utilisateur de l'hôte), pas root du conteneur : les sauvegardes restent lisibles.
|
||||
chown "$(stat -c %u:%g /backups)" "${file}" 2>/dev/null || true
|
||||
echo "sauvegarde : ${file}"
|
||||
ls -1 /backups/pyquest-*.sql.gz | sort | head -n "-${KEEP}" | xargs -r rm -f --
|
||||
else
|
||||
rm -f "${file}.part"
|
||||
echo "SAUVEGARDE ÉCHOUÉE" >&2
|
||||
fi
|
||||
sleep 86400
|
||||
done
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Sauvegarde quotidienne de la base SQLite (conteneur « backup » du compose intranet, image du backend). Copie
|
||||
# cohérente par l'API de sauvegarde de SQLite, sûre même si le backend écrit en même temps.
|
||||
set -eu
|
||||
KEEP="${PYQUEST_BACKUP_KEEP:-14}"
|
||||
umask 077
|
||||
while :; do
|
||||
file="/backups/pyquest-$(date +%Y%m%d-%H%M%S).sqlite.gz"
|
||||
if python - "${PYQUEST_DB_PATH}" "${file}.db" <<'PY' && gzip -9 < "${file}.db" > "${file}.part" && [ "$(gunzip -c "${file}.part" | wc -c)" -gt 500 ]
|
||||
import sqlite3, sys
|
||||
source = sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True)
|
||||
target = sqlite3.connect(sys.argv[2])
|
||||
with target:
|
||||
source.backup(target)
|
||||
target.close()
|
||||
source.close()
|
||||
PY
|
||||
then
|
||||
mv "${file}.part" "${file}"
|
||||
# Propriétaire du dossier monté (l'utilisateur de l'hôte), pas root du conteneur : les sauvegardes restent lisibles.
|
||||
chown "$(stat -c %u:%g /backups)" "${file}" 2>/dev/null || true
|
||||
echo "sauvegarde : ${file}"
|
||||
ls -1 /backups/pyquest-*.sqlite.gz | sort | head -n "-${KEEP}" | xargs -r rm -f --
|
||||
else
|
||||
rm -f "${file}.part"
|
||||
echo "SAUVEGARDE ÉCHOUÉE" >&2
|
||||
fi
|
||||
rm -f "${file}.db"
|
||||
sleep 86400
|
||||
done
|
||||
@@ -0,0 +1,71 @@
|
||||
# PyQuest dans un réseau interne (lycée) avec Docker : nginx (HTTPS avec une autorité de certification interne),
|
||||
# Django/gunicorn, base SQLite, sauvegarde quotidienne. Prêt à l'emploi : lancer ./docker/setup.sh intranet (génère les
|
||||
# secrets dans docker/.env.intranet, construit, démarre). Détails : docs/site/fr/host/docker.md
|
||||
#
|
||||
# docker compose -f docker/compose.intranet.yaml --env-file docker/.env.intranet up -d
|
||||
name: pyquest-intranet
|
||||
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
target: backend
|
||||
image: pyquest/backend:local
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
environment: &backend-env
|
||||
DJANGO_SETTINGS_MODULE: pyquest_api.settings.production
|
||||
PYQUEST_SECRET_KEY: ${PYQUEST_SECRET_KEY:?lancer ./docker/setup.sh intranet}
|
||||
PYQUEST_ALLOWED_HOSTS: ${PYQUEST_HOSTS:?}
|
||||
PYQUEST_ORIGIN: ${PYQUEST_ORIGINS:?}
|
||||
PYQUEST_DB_ENGINE: sqlite
|
||||
PYQUEST_DB_PATH: /var/lib/pyquest/db.sqlite3
|
||||
PYQUEST_STATIC_ROOT: /var/www/pyquest/static
|
||||
volumes:
|
||||
- data:/var/lib/pyquest
|
||||
- static:/var/www/pyquest/static
|
||||
|
||||
web:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
target: web
|
||||
image: pyquest/web:local
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
environment:
|
||||
PYQUEST_MODE: intranet
|
||||
PYQUEST_HOSTS: ${PYQUEST_HOSTS:?}
|
||||
PYQUEST_PUBLIC_HTTPS_PORT: ${PYQUEST_HTTPS_PORT:-443}
|
||||
ports:
|
||||
- "${PYQUEST_HTTP_PORT:-80}:80"
|
||||
- "${PYQUEST_HTTPS_PORT:-443}:443"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- static:/var/www/pyquest/static:ro
|
||||
# Autorité de certification et certificat du serveur : à sauvegarder (ca.key surtout), voir la documentation.
|
||||
- tls:/etc/pyquest/tls
|
||||
|
||||
backup:
|
||||
image: pyquest/backend:local
|
||||
restart: unless-stopped
|
||||
entrypoint: ["/bin/sh", "/backup.sh"]
|
||||
healthcheck:
|
||||
disable: true
|
||||
environment:
|
||||
<<: *backend-env
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- data:/var/lib/pyquest:ro
|
||||
- ./backup/sqlite-backup.sh:/backup.sh:ro
|
||||
- ${PYQUEST_BACKUP_DIR:-./backups}:/backups
|
||||
|
||||
volumes:
|
||||
data:
|
||||
static:
|
||||
tls:
|
||||
@@ -0,0 +1,106 @@
|
||||
# PyQuest sur un VPS public avec Docker : nginx (HTTPS Let's Encrypt), Django/gunicorn, MariaDB, renouvellement du
|
||||
# certificat et sauvegarde quotidienne. Prêt à l'emploi : lancer ./docker/setup.sh vps (génère les secrets dans
|
||||
# docker/.env.vps, construit, démarre, obtient le certificat). Détails : docs/site/fr/host/docker.md
|
||||
#
|
||||
# docker compose -f docker/compose.vps.yaml --env-file docker/.env.vps up -d
|
||||
name: pyquest-vps
|
||||
|
||||
x-backend-env: &backend-env
|
||||
DJANGO_SETTINGS_MODULE: pyquest_api.settings.production
|
||||
PYQUEST_SECRET_KEY: ${PYQUEST_SECRET_KEY:?lancer ./docker/setup.sh vps}
|
||||
PYQUEST_ALLOWED_HOSTS: ${PYQUEST_DOMAIN:?}
|
||||
PYQUEST_ORIGIN: https://${PYQUEST_DOMAIN}${PYQUEST_ORIGIN_PORT:-}
|
||||
PYQUEST_DB_NAME: pyquest
|
||||
PYQUEST_DB_USER: pyquest
|
||||
PYQUEST_DB_PASSWORD: ${PYQUEST_DB_PASSWORD:?}
|
||||
PYQUEST_DB_HOST: db
|
||||
PYQUEST_STATIC_ROOT: /var/www/pyquest/static
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mariadb:11.4
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MARIADB_DATABASE: pyquest
|
||||
MARIADB_USER: pyquest
|
||||
MARIADB_PASSWORD: ${PYQUEST_DB_PASSWORD:?}
|
||||
MARIADB_RANDOM_ROOT_PASSWORD: "1"
|
||||
command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"]
|
||||
volumes:
|
||||
- db:/var/lib/mysql
|
||||
healthcheck:
|
||||
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 30s
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
target: backend
|
||||
image: pyquest/backend:local
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
environment: *backend-env
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- static:/var/www/pyquest/static
|
||||
|
||||
web:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
target: web
|
||||
image: pyquest/web:local
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
environment:
|
||||
PYQUEST_MODE: vps
|
||||
PYQUEST_DOMAIN: ${PYQUEST_DOMAIN:?}
|
||||
PYQUEST_PUBLIC_HTTPS_PORT: ${PYQUEST_HTTPS_PORT:-443}
|
||||
ports:
|
||||
- "${PYQUEST_HTTP_PORT:-80}:80"
|
||||
- "${PYQUEST_HTTPS_PORT:-443}:443"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- static:/var/www/pyquest/static:ro
|
||||
- letsencrypt:/etc/letsencrypt:ro
|
||||
- acme:/var/www/letsencrypt
|
||||
|
||||
# Renouvellement : vérifie deux fois par jour ; nginx recharge le nouveau certificat dans les 6 heures.
|
||||
certbot:
|
||||
image: certbot/certbot:latest
|
||||
restart: unless-stopped
|
||||
entrypoint: ["/bin/sh", "-c", "trap exit TERM; while :; do certbot renew --webroot -w /var/www/letsencrypt --quiet; sleep 12h & wait $${!}; done"]
|
||||
depends_on:
|
||||
- web
|
||||
volumes:
|
||||
- letsencrypt:/etc/letsencrypt
|
||||
- acme:/var/www/letsencrypt
|
||||
|
||||
backup:
|
||||
image: mariadb:11.4
|
||||
restart: unless-stopped
|
||||
entrypoint: ["/bin/sh", "/backup.sh"]
|
||||
environment:
|
||||
MARIADB_USER: pyquest
|
||||
MARIADB_DATABASE: pyquest
|
||||
MYSQL_PWD: ${PYQUEST_DB_PASSWORD:?}
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./backup/mariadb-backup.sh:/backup.sh:ro
|
||||
- ${PYQUEST_BACKUP_DIR:-./backups}:/backups
|
||||
|
||||
volumes:
|
||||
db:
|
||||
static:
|
||||
letsencrypt:
|
||||
acme:
|
||||
@@ -0,0 +1,10 @@
|
||||
# Modèle de docker/.env.intranet (créé par ./docker/setup.sh intranet, qui génère le secret). JAMAIS commité avec de vraies valeurs.
|
||||
# Noms et adresses IP par lesquels les postes joignent le serveur (séparés par des virgules, sans espace).
|
||||
PYQUEST_HOSTS=pyquest.lycee.local,192.168.1.20
|
||||
PYQUEST_ORIGINS=https://pyquest.lycee.local,https://192.168.1.20
|
||||
PYQUEST_SECRET_KEY=__A_GENERER__
|
||||
# Ports publiés sur l'hôte (essais ; en production laisser 80 et 443). Si HTTPS n'est pas sur 443, mettre le port dans
|
||||
# PYQUEST_ORIGINS (https://hôte:8443).
|
||||
PYQUEST_HTTP_PORT=80
|
||||
PYQUEST_HTTPS_PORT=443
|
||||
PYQUEST_BACKUP_DIR=./backups
|
||||
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env bash
|
||||
# Mise en route de PyQuest avec Docker Compose, d'une seule commande (Docker et le plugin « compose » requis) :
|
||||
#
|
||||
# ./docker/setup.sh vps --domain pyquest.example.org --email toi@example.org
|
||||
# ./docker/setup.sh intranet --host pyquest.lycee.local,192.168.1.20
|
||||
#
|
||||
# Génère les secrets dans docker/.env.<mode> (jamais écrasé), construit les images (le site et le moteur Python sont
|
||||
# construits dans l'image), démarre les services, puis : VPS → obtient le certificat Let's Encrypt ; intranet → l'autorité
|
||||
# de certification interne est créée au premier démarrage. Relançable sans danger.
|
||||
#
|
||||
# Options : --domain, --email (vps) ; --host (intranet) ; --http-port N, --https-port N (essais, défaut 80 et 443) ;
|
||||
# --no-admin (ne pas proposer de créer l'administrateur) ; --yes (aucune question) ; --dry-run
|
||||
# Ensuite : docker compose -f docker/compose.<mode>.yaml --env-file docker/.env.<mode> ps | logs -f | down
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO="$(cd "${HERE}/.." && pwd)"
|
||||
ASSUME_YES=0; DRY_RUN=0
|
||||
# shellcheck source=deploy/lib.sh
|
||||
. "${REPO}/deploy/lib.sh"
|
||||
|
||||
MODE="${1:-}"
|
||||
case "${MODE}" in vps|intranet) shift ;; -h|--help) sed -n '2,13p' "${BASH_SOURCE[0]}"; exit 0 ;; *) sed -n '2,13p' "${BASH_SOURCE[0]}" >&2; exit 2 ;; esac
|
||||
DOMAIN=""; EMAIL=""; HOSTS=""; HTTP_PORT=""; HTTPS_PORT=""; CREATE_ADMIN=1; STAGING=0
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--domain) DOMAIN="${2:-}"; shift 2 ;;
|
||||
--email) EMAIL="${2:-}"; shift 2 ;;
|
||||
--host) HOSTS="${2:-}"; shift 2 ;;
|
||||
--http-port) HTTP_PORT="${2:-}"; shift 2 ;;
|
||||
--https-port) HTTPS_PORT="${2:-}"; shift 2 ;;
|
||||
--staging) STAGING=1; shift ;;
|
||||
--no-admin) CREATE_ADMIN=0; shift ;;
|
||||
--yes) ASSUME_YES=1; shift ;;
|
||||
--dry-run) DRY_RUN=1; shift ;;
|
||||
-h|--help) sed -n '2,13p' "${BASH_SOURCE[0]}"; exit 0 ;;
|
||||
*) echo "Option inconnue : $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
command -v docker >/dev/null || die "Docker n'est pas installé."
|
||||
docker compose version >/dev/null 2>&1 || die "le plugin « docker compose » est requis (Docker 20.10 ou plus récent)."
|
||||
for port in "${HTTP_PORT}" "${HTTPS_PORT}"; do
|
||||
[[ -z "${port}" || "${port}" =~ ^[0-9]{2,5}$ ]] || die "port invalide : ${port}"
|
||||
done
|
||||
|
||||
cd "${REPO}" # commandes affichées avec des chemins relatifs, à copier telles quelles depuis la racine du dépôt
|
||||
ENV_FILE="docker/.env.${MODE}"
|
||||
COMPOSE=(docker compose -f "docker/compose.${MODE}.yaml" --env-file "${ENV_FILE}")
|
||||
secret() { python3 -c 'import secrets; print(secrets.token_urlsafe(64))'; }
|
||||
password() { python3 -c 'import secrets, string; print("".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(32)))'; }
|
||||
|
||||
# ---- fichier d'environnement -----------------------------------------------------------------------------------------
|
||||
step "Réglages (${ENV_FILE})"
|
||||
if [[ -e "${ENV_FILE}" ]]; then
|
||||
echo "déjà présent, conservé : ${ENV_FILE}"
|
||||
else
|
||||
if [[ "${MODE}" == vps ]]; then
|
||||
ask DOMAIN "Nom de domaine du site (ex. pyquest.example.org)"
|
||||
ask EMAIL "Adresse e-mail pour Let's Encrypt"
|
||||
[[ "${DOMAIN}" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "domaine invalide : ${DOMAIN}"
|
||||
[[ "${EMAIL}" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[A-Za-z]{2,}$ ]] || die "adresse e-mail invalide : ${EMAIL}"
|
||||
else
|
||||
ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
|
||||
ask HOSTS "Noms ou adresses IP du serveur, séparés par des virgules" "$(hostname -f 2>/dev/null || hostname)${ip:+,${ip}}"
|
||||
HOSTS="${HOSTS//, /,}"
|
||||
IFS=, read -r -a HOST_LIST <<< "${HOSTS}"
|
||||
for host in "${HOST_LIST[@]}"; do
|
||||
[[ "${host}" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ || "${host}" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ ]] || die "nom ou adresse invalide : ${host}"
|
||||
done
|
||||
fi
|
||||
if [[ "${DRY_RUN}" == 1 ]]; then
|
||||
echo "[dry-run] création de ${ENV_FILE} (secrets générés)"
|
||||
else
|
||||
origin_suffix=""
|
||||
[[ -z "${HTTPS_PORT}" || "${HTTPS_PORT}" == 443 ]] || origin_suffix=":${HTTPS_PORT}"
|
||||
umask 077
|
||||
if [[ "${MODE}" == vps ]]; then
|
||||
sed -e "s#^PYQUEST_DOMAIN=.*#PYQUEST_DOMAIN=${DOMAIN}#" -e "s#^PYQUEST_EMAIL=.*#PYQUEST_EMAIL=${EMAIL}#" \
|
||||
-e "0,/__A_GENERER__/s##$(secret)#" -e "0,/__A_GENERER__/s##$(password)#" "docker/vps.env.example" > "${ENV_FILE}"
|
||||
[[ -z "${origin_suffix}" ]] || echo "PYQUEST_ORIGIN_PORT=${origin_suffix}" >> "${ENV_FILE}"
|
||||
else
|
||||
origins=""
|
||||
for host in "${HOST_LIST[@]}"; do origins+="https://${host}${origin_suffix},"; done
|
||||
sed -e "s#^PYQUEST_HOSTS=.*#PYQUEST_HOSTS=${HOSTS}#" -e "s#^PYQUEST_ORIGINS=.*#PYQUEST_ORIGINS=${origins%,}#" \
|
||||
-e "s#__A_GENERER__#$(secret)#" "docker/intranet.env.example" > "${ENV_FILE}"
|
||||
fi
|
||||
[[ -z "${HTTP_PORT}" ]] || envset "${ENV_FILE}" PYQUEST_HTTP_PORT "${HTTP_PORT}"
|
||||
[[ -z "${HTTPS_PORT}" ]] || envset "${ENV_FILE}" PYQUEST_HTTPS_PORT "${HTTPS_PORT}"
|
||||
echo "créé : ${ENV_FILE} (droits 600)"
|
||||
fi
|
||||
fi
|
||||
[[ "${DRY_RUN}" == 1 ]] && { echo "[dry-run] ${COMPOSE[*]} up -d --build"; exit 0; }
|
||||
DOMAIN="$(envval "${ENV_FILE}" PYQUEST_DOMAIN)"; EMAIL="$(envval "${ENV_FILE}" PYQUEST_EMAIL)"
|
||||
HOSTS="$(envval "${ENV_FILE}" PYQUEST_HOSTS)"
|
||||
HTTPS_PORT="$(envval "${ENV_FILE}" PYQUEST_HTTPS_PORT)"; HTTPS_PORT="${HTTPS_PORT:-443}"
|
||||
backup_dir="$(envval "${ENV_FILE}" PYQUEST_BACKUP_DIR)"; backup_dir="${backup_dir:-./backups}"
|
||||
case "${backup_dir}" in /*) mkdir -p "${backup_dir}" ;; *) mkdir -p "docker/${backup_dir#./}" ;; esac
|
||||
|
||||
# ---- construction et démarrage -----------------------------------------------------------------------------------------
|
||||
step "Construction des images (la première fois : téléchargement du moteur Python et des dépendances, quelques minutes)"
|
||||
"${COMPOSE[@]}" build
|
||||
step "Démarrage"
|
||||
"${COMPOSE[@]}" up -d --wait --wait-timeout 180 web || { "${COMPOSE[@]}" logs --tail 40 >&2; die "les services ne démarrent pas : voir les journaux ci-dessus."; }
|
||||
|
||||
# ---- certificat Let's Encrypt (VPS) ---------------------------------------------------------------------------------------
|
||||
if [[ "${MODE}" == vps ]]; then
|
||||
step "Certificat Let's Encrypt pour ${DOMAIN}"
|
||||
if "${COMPOSE[@]}" run --rm --no-deps -T --entrypoint sh certbot -c "test -e /etc/letsencrypt/live/${DOMAIN}/fullchain.pem"; then
|
||||
echo "déjà obtenu"
|
||||
else
|
||||
staging=(); [[ "${STAGING}" == 0 ]] || staging=(--staging)
|
||||
"${COMPOSE[@]}" run --rm --no-deps -T --entrypoint certbot certbot certonly --webroot -w /var/www/letsencrypt \
|
||||
-d "${DOMAIN}" -m "${EMAIL}" --agree-tos --non-interactive "${staging[@]}" \
|
||||
|| die "certificat non obtenu : le DNS de ${DOMAIN} pointe-t-il vers ce serveur, les ports 80 et 443 sont-ils joignables ? Relance la commande ensuite."
|
||||
"${COMPOSE[@]}" exec -T web pyquest-tls reload
|
||||
fi
|
||||
fi
|
||||
|
||||
# ---- administrateur ------------------------------------------------------------------------------------------------------
|
||||
if [[ "${CREATE_ADMIN}" == 1 && "${ASSUME_YES}" == 0 && -t 0 ]]; then
|
||||
if confirm "Créer maintenant le premier administrateur (accès à /api/admin/ pour gérer les auteurs) ?"; then
|
||||
"${COMPOSE[@]}" exec backend python manage.py createsuperuser || echo "Administrateur non créé : voir la commande ci-dessous."
|
||||
fi
|
||||
fi
|
||||
|
||||
first="${DOMAIN:-${HOSTS%%,*}}"
|
||||
port_suffix=""; [[ "${HTTPS_PORT}" == 443 ]] || port_suffix=":${HTTPS_PORT}"
|
||||
HTTP_PORT="$(envval "${ENV_FILE}" PYQUEST_HTTP_PORT)"; HTTP_SUFFIX=""; [[ -z "${HTTP_PORT}" || "${HTTP_PORT}" == 80 ]] || HTTP_SUFFIX=":${HTTP_PORT}"
|
||||
cat <<NEXT
|
||||
|
||||
==> PyQuest est en ligne : https://${first}${port_suffix}/
|
||||
- Administrateur : ${COMPOSE[*]} exec backend python manage.py createsuperuser
|
||||
- État / journaux / arrêt : ${COMPOSE[*]} ps | logs -f | down
|
||||
- Mise à jour : git pull && ${COMPOSE[*]} up -d --build
|
||||
NEXT
|
||||
if [[ "${MODE}" == intranet ]]; then
|
||||
cat <<NEXT
|
||||
- Postes : faire confiance à l'autorité interne UNE fois (page http://${first}${HTTP_SUFFIX}/ca) ; sans cela le navigateur
|
||||
avertit et le mode hors ligne ne fonctionne pas.
|
||||
- Sauvegarder la clé de l'autorité, hors du serveur : ${COMPOSE[*]} cp web:/etc/pyquest/tls/ca.key ./ca.key
|
||||
NEXT
|
||||
fi
|
||||
@@ -0,0 +1,11 @@
|
||||
# Modèle de docker/.env.vps (créé par ./docker/setup.sh vps, qui génère les secrets). JAMAIS commité avec de vraies valeurs.
|
||||
PYQUEST_DOMAIN=pyquest.example.org
|
||||
PYQUEST_EMAIL=toi@example.org
|
||||
PYQUEST_SECRET_KEY=__A_GENERER__
|
||||
PYQUEST_DB_PASSWORD=__A_GENERER__
|
||||
# Ports publiés sur l'hôte (essais ; en production laisser 80 et 443). Si HTTPS n'est pas sur 443, ajouter
|
||||
# PYQUEST_ORIGIN_PORT=:8443
|
||||
PYQUEST_HTTP_PORT=80
|
||||
PYQUEST_HTTPS_PORT=443
|
||||
# Dossier des sauvegardes quotidiennes de la base (sur l'hôte).
|
||||
PYQUEST_BACKUP_DIR=./backups
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
# Exécuté par l'entrée standard de l'image nginx avant son démarrage : vhost selon le mode, certificats, puis
|
||||
# surveillance périodique (renouvellement et rechargement) en arrière-plan.
|
||||
set -euo pipefail
|
||||
pyquest-tls render
|
||||
pyquest-tls ensure
|
||||
nohup pyquest-tls loop >/proc/1/fd/1 2>&1 &
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/bin/bash
|
||||
# Gestion du vhost et des certificats du conteneur web.
|
||||
# pyquest-tls render écrit /etc/nginx/conf.d/pyquest.conf selon PYQUEST_MODE (vps | intranet)
|
||||
# pyquest-tls ensure met en place les certificats (VPS : Let's Encrypt s'il existe, sinon provisoire ; intranet :
|
||||
# autorité et certificat internes, réémis si besoin)
|
||||
# pyquest-tls reload ensure + rechargement de nginx (après un renouvellement)
|
||||
# pyquest-tls loop reload toutes les 6 heures
|
||||
set -euo pipefail
|
||||
|
||||
MODE="${PYQUEST_MODE:?PYQUEST_MODE doit valoir vps ou intranet}"
|
||||
TLS=/etc/nginx/tls
|
||||
INTRANET_TLS=/etc/pyquest/tls
|
||||
PUBLIC_HTTPS_PORT="${PYQUEST_PUBLIC_HTTPS_PORT:-443}"
|
||||
say() { printf '[pyquest-tls] %s\n' "$*"; }
|
||||
|
||||
render() {
|
||||
local conf=/etc/nginx/conf.d/pyquest.conf
|
||||
# Le relais vers Django passe par le DNS de Docker (resolver) : voir l'extrait pyquest-locations.conf de l'image.
|
||||
local upstream=' resolver 127.0.0.11 valid=10s ipv6=off;\n set $pq_upstream backend:8000;'
|
||||
case "${MODE}" in
|
||||
vps)
|
||||
local domain="${PYQUEST_DOMAIN:?PYQUEST_DOMAIN requis}"
|
||||
sed -e "s#pyquest.example.org#${domain}#g" \
|
||||
-e "s#/etc/letsencrypt/live/${domain}/fullchain.pem#${TLS}/fullchain.pem#" \
|
||||
-e "s#/etc/letsencrypt/live/${domain}/privkey.pem#${TLS}/privkey.pem#" \
|
||||
-e "s#/var/www/letsencrypt#/var/www/letsencrypt#" \
|
||||
-e "/http2 on;/a\\${upstream}" \
|
||||
/opt/pyquest/nginx/pyquest.conf.example > "${conf}"
|
||||
;;
|
||||
intranet)
|
||||
local hosts="${PYQUEST_HOSTS:?PYQUEST_HOSTS requis (noms ou adresses séparés par des virgules)}"
|
||||
sed -e "s#__SERVER_NAMES__#${hosts//,/ }#" -e "s#__WEB_ROOT__#/var/www/pyquest#g" -e "s#__TLS_DIR__#${INTRANET_TLS}#g" \
|
||||
-e "/http2 on;/a\\${upstream}" \
|
||||
/opt/pyquest/nginx/pyquest-intranet.conf.example > "${conf}"
|
||||
;;
|
||||
*) say "PYQUEST_MODE inconnu : ${MODE}"; exit 1 ;;
|
||||
esac
|
||||
# Port public de HTTPS différent de 443 (essais, port déjà pris) : la redirection doit l'indiquer.
|
||||
if [[ "${PUBLIC_HTTPS_PORT}" != 443 ]]; then
|
||||
sed -i "s#https://\$host\$request_uri#https://\$host:${PUBLIC_HTTPS_PORT}\$request_uri#" "${conf}"
|
||||
fi
|
||||
say "vhost écrit pour le mode ${MODE}"
|
||||
}
|
||||
|
||||
ensure() {
|
||||
mkdir -p "${TLS}"
|
||||
case "${MODE}" in
|
||||
vps)
|
||||
local live="/etc/letsencrypt/live/${PYQUEST_DOMAIN}"
|
||||
if [[ -r "${live}/fullchain.pem" && -r "${live}/privkey.pem" ]]; then
|
||||
ln -sfn "${live}/fullchain.pem" "${TLS}/fullchain.pem"
|
||||
ln -sfn "${live}/privkey.pem" "${TLS}/privkey.pem"
|
||||
else
|
||||
# nginx doit démarrer avant d'obtenir le certificat (le défi Let's Encrypt passe par lui) : certificat provisoire.
|
||||
if [[ ! -s "${TLS}/placeholder.crt" ]]; then
|
||||
openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 30 \
|
||||
-keyout "${TLS}/placeholder.key" -out "${TLS}/placeholder.crt" -subj "/CN=${PYQUEST_DOMAIN}" 2>/dev/null
|
||||
fi
|
||||
ln -sfn "${TLS}/placeholder.crt" "${TLS}/fullchain.pem"
|
||||
ln -sfn "${TLS}/placeholder.key" "${TLS}/privkey.pem"
|
||||
say "pas encore de certificat Let's Encrypt pour ${PYQUEST_DOMAIN} : certificat provisoire (voir la documentation)"
|
||||
fi
|
||||
;;
|
||||
intranet)
|
||||
intranet_cert.sh --hosts "${PYQUEST_HOSTS}" --dir "${INTRANET_TLS}" --if-needed | grep -v '^RELOAD_NEEDED$' || true
|
||||
install -m 644 "${INTRANET_TLS}/ca.crt" /var/www/pyquest/ca/pyquest-ca.crt
|
||||
install -m 644 /opt/pyquest/intranet-ca.html /var/www/pyquest/ca/index.html
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
render) render ;;
|
||||
ensure) ensure ;;
|
||||
reload) ensure; nginx -t 2>/dev/null && nginx -s reload && say "nginx rechargé" ;;
|
||||
loop) while sleep 6h; do "$0" reload || say "rechargement en échec"; done ;;
|
||||
*) sed -n '2,7p' "$0"; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,72 @@
|
||||
# Docker Compose: VPS and intranet
|
||||
|
||||
An alternative to the [installers](installers.md): the whole stack runs in containers, with nothing installed on the host
|
||||
except Docker (with the `docker compose` plugin). Two ready-to-use files, one per situation:
|
||||
|
||||
| | Public VPS | Intranet (school network) |
|
||||
|---|---|---|
|
||||
| File | `docker/compose.vps.yaml` | `docker/compose.intranet.yaml` |
|
||||
| Command | `./docker/setup.sh vps` | `./docker/setup.sh intranet` |
|
||||
| HTTPS | **Let's Encrypt** (`certbot` service, automatic renewal) | **internal certificate authority** created on first start |
|
||||
| Database | **MariaDB** (`db` service) | **SQLite** (`data` volume) |
|
||||
| Services | `web` (nginx), `backend` (Django), `db`, `certbot`, `backup` | `web`, `backend`, `backup` |
|
||||
|
||||
The images contain the site and the Python engine (Pyodide, downloaded and verified at build time): **no `make build`
|
||||
needed**, and the server needs no Internet access once the images are built.
|
||||
|
||||
## VPS
|
||||
|
||||
Requirements: Docker, the domain name pointing to the VPS, ports 80 and 443 free.
|
||||
|
||||
```bash
|
||||
git clone git@github.com:deunix-educ/PyQuest.git /opt/PyQuest && cd /opt/PyQuest
|
||||
./docker/setup.sh vps --domain pyquest.example.org --email you@example.org
|
||||
```
|
||||
|
||||
The script generates the secrets in `docker/.env.vps` (mode 600, never committed, never overwritten), builds the images,
|
||||
starts the stack with a temporary certificate (nginx must answer for Let's Encrypt to validate the domain), obtains the
|
||||
real certificate, activates it, then offers to create the first administrator. Add `--staging` to try with Let's
|
||||
Encrypt's test server (no rate limits).
|
||||
|
||||
## Intranet
|
||||
|
||||
```bash
|
||||
./docker/setup.sh intranet --host pyquest.school.lan,192.168.1.20
|
||||
```
|
||||
|
||||
Same principle: secrets in `docker/.env.intranet`, internal authority and certificate created on first start in the `tls`
|
||||
volume (the certificate is reissued automatically before it expires, the authority does not change). **Computers must
|
||||
trust the authority once**: page `http://<server>/ca` (see [The installers](installers.md), intranet section, including
|
||||
one browser profile per student). **Back up the authority's key off the server**:
|
||||
`docker compose -f docker/compose.intranet.yaml --env-file docker/.env.intranet cp web:/etc/pyquest/tls/ca.key ./ca.key`.
|
||||
|
||||
## Operations
|
||||
|
||||
Run all commands from the repository root (replace `vps` with `intranet` as needed):
|
||||
|
||||
```bash
|
||||
PQ="docker compose -f docker/compose.vps.yaml --env-file docker/.env.vps"
|
||||
$PQ ps # service status
|
||||
$PQ logs -f backend # logs
|
||||
$PQ exec backend python manage.py createsuperuser # administrator (author management: /api/admin/)
|
||||
git pull && $PQ up -d --build # update (data, kept in volumes, is preserved)
|
||||
$PQ down # stop (WITHOUT -v: "down -v" deletes the volumes, hence the data)
|
||||
```
|
||||
|
||||
- **Data**: Docker volumes `db` (MariaDB) or `data` (SQLite), `letsencrypt`, `tls`. An automatic database backup (daily,
|
||||
14 kept) is written to `docker/backups/` (`PYQUEST_BACKUP_DIR`); remember to copy it off the server.
|
||||
- **Restoring**: MariaDB, `gunzip < backup.sql.gz | $PQ exec -T db sh -c 'mariadb -u pyquest -p"$MARIADB_PASSWORD" pyquest'`;
|
||||
SQLite, stop `backend`, then replace `/var/lib/pyquest/db.sqlite3` in the `data` volume with the decompressed backup.
|
||||
- **Let's Encrypt renewal**: `certbot` checks twice a day; nginx reloads the certificate within six hours at most (or
|
||||
immediately: `$PQ exec web pyquest-tls reload`).
|
||||
- **Ports**: Docker publishes 80 and 443 bypassing `ufw` rules; restrict access with the provider's firewall if needed.
|
||||
For tests, `--http-port` and `--https-port` pick other ports.
|
||||
- **Rate limiting**: it relies on the IP address nginx sees. On a standard Docker host this is the client's; behind another
|
||||
proxy it would be the proxy's.
|
||||
|
||||
## Verified
|
||||
|
||||
`make test-docker` builds the images, starts both stacks on free ports, queries nginx over HTTPS (isolation headers,
|
||||
Python engine, protected editor, administration, static files, synchronisation, database, backups, backend restart,
|
||||
authority persistence) and tears everything down. **Not verified for real**: obtaining the Let's Encrypt certificate (the
|
||||
HTTP challenge is tested, not the exchange with Let's Encrypt) and a renewal at expiry.
|
||||
@@ -1,5 +1,8 @@
|
||||
# The installers: VPS and intranet
|
||||
|
||||
!!! tip "With Docker"
|
||||
If you prefer containers, `./docker/setup.sh vps|intranet` does the same: see [Docker Compose](docker.md).
|
||||
|
||||
Two scripts do, **in one command**, everything you would otherwise do by hand. Run them **as root on the server**, from a
|
||||
clone of the repository (outside `/root` and `/home`, e.g. `/opt/PyQuest`), on **Debian or Ubuntu**. They are
|
||||
**idempotent**: after an interruption, run the same command again. `--dry-run` prints everything that would be done
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Docker Compose : VPS et intranet
|
||||
|
||||
Alternative aux [installateurs](installers.md) : toute la pile tourne dans des conteneurs, sans rien installer sur
|
||||
l'hôte à part Docker (avec le plugin `docker compose`). Deux fichiers prêts à l'emploi, un par situation :
|
||||
|
||||
| | VPS public | Réseau intranet (lycée) |
|
||||
|---|---|---|
|
||||
| Fichier | `docker/compose.vps.yaml` | `docker/compose.intranet.yaml` |
|
||||
| Commande | `./docker/setup.sh vps` | `./docker/setup.sh intranet` |
|
||||
| HTTPS | **Let's Encrypt** (service `certbot`, renouvellement automatique) | **autorité de certification interne** créée au premier démarrage |
|
||||
| Base | **MariaDB** (service `db`) | **SQLite** (volume `data`) |
|
||||
| Services | `web` (nginx), `backend` (Django), `db`, `certbot`, `backup` | `web`, `backend`, `backup` |
|
||||
|
||||
Les images contiennent le site et le moteur Python (Pyodide, téléchargé et vérifié à la construction) : **aucun
|
||||
`make build` à faire**, et le serveur n'a pas besoin d'Internet une fois les images construites.
|
||||
|
||||
## VPS
|
||||
|
||||
Prérequis : Docker, le nom de domaine qui pointe vers le VPS, les ports 80 et 443 libres.
|
||||
|
||||
```bash
|
||||
git clone git@github.com:deunix-educ/PyQuest.git /opt/PyQuest && cd /opt/PyQuest
|
||||
./docker/setup.sh vps --domain pyquest.example.org --email toi@example.org
|
||||
```
|
||||
|
||||
Le script génère les secrets dans `docker/.env.vps` (droits 600, jamais commité, jamais écrasé), construit les images,
|
||||
démarre la pile avec un certificat provisoire (nginx doit répondre pour que Let's Encrypt valide le domaine), obtient le
|
||||
vrai certificat, le met en service, puis propose de créer le premier administrateur. Ajoute `--staging` pour essayer avec
|
||||
le serveur de test de Let's Encrypt (pas de limite de débit).
|
||||
|
||||
## Intranet
|
||||
|
||||
```bash
|
||||
./docker/setup.sh intranet --host pyquest.lycee.local,192.168.1.20
|
||||
```
|
||||
|
||||
Même principe : secrets dans `docker/.env.intranet`, autorité et certificat internes créés au premier démarrage dans le
|
||||
volume `tls` (le certificat est réémis automatiquement avant son expiration, l'autorité ne change pas). Les **postes
|
||||
doivent faire confiance à l'autorité une fois** : page `http://<serveur>/ca` (voir [Les installateurs](installers.md),
|
||||
section intranet, y compris le profil de navigateur par élève). **Sauvegarde la clé de l'autorité hors du serveur** :
|
||||
`docker compose -f docker/compose.intranet.yaml --env-file docker/.env.intranet cp web:/etc/pyquest/tls/ca.key ./ca.key`.
|
||||
|
||||
## Exploitation
|
||||
|
||||
Toutes les commandes se lancent depuis la racine du dépôt (remplacer `vps` par `intranet` selon le cas) :
|
||||
|
||||
```bash
|
||||
PQ="docker compose -f docker/compose.vps.yaml --env-file docker/.env.vps"
|
||||
$PQ ps # état des services
|
||||
$PQ logs -f backend # journaux
|
||||
$PQ exec backend python manage.py createsuperuser # administrateur (gestion des auteurs : /api/admin/)
|
||||
git pull && $PQ up -d --build # mise à jour (les données, dans des volumes, sont conservées)
|
||||
$PQ down # arrêt (SANS -v : « down -v » supprime les volumes, donc les données)
|
||||
```
|
||||
|
||||
- **Données** : volumes Docker `db` (MariaDB) ou `data` (SQLite), `letsencrypt`, `tls`. Une sauvegarde automatique de la
|
||||
base (quotidienne, 14 conservées) est écrite dans `docker/backups/` (`PYQUEST_BACKUP_DIR`) ; pense à la copier hors du
|
||||
serveur.
|
||||
- **Restauration** : MariaDB, `gunzip < sauvegarde.sql.gz | $PQ exec -T db sh -c 'mariadb -u pyquest -p"$MARIADB_PASSWORD" pyquest'` ;
|
||||
SQLite, arrêter `backend` puis remplacer `/var/lib/pyquest/db.sqlite3` dans le volume `data` par la sauvegarde décompressée.
|
||||
- **Renouvellement Let's Encrypt** : `certbot` vérifie deux fois par jour ; nginx recharge le certificat au plus tard six
|
||||
heures après (ou tout de suite : `$PQ exec web pyquest-tls reload`).
|
||||
- **Ports** : Docker publie 80 et 443 en contournant les règles `ufw` ; restreindre l'accès avec le pare-feu du fournisseur
|
||||
si besoin. Pour des essais, `--http-port` et `--https-port` choisissent d'autres ports.
|
||||
- **Limitation de débit** : elle repose sur l'adresse IP vue par nginx. Sur un hôte Docker standard c'est celle du client ;
|
||||
derrière un autre proxy, elle serait celle du proxy.
|
||||
|
||||
## Vérifié
|
||||
|
||||
`make test-docker` construit les images, démarre les deux piles sur des ports libres, interroge nginx en HTTPS (en-têtes
|
||||
d'isolation, moteur Python, éditeur protégé, administration, fichiers statiques, synchronisation, base, sauvegardes,
|
||||
redémarrage du backend, persistance de l'autorité) et détruit tout. **Non vérifié en réel** : l'obtention du certificat
|
||||
Let's Encrypt (le défi HTTP est testé, pas l'échange avec Let's Encrypt) et un renouvellement à l'échéance.
|
||||
@@ -1,5 +1,8 @@
|
||||
# Les installateurs : VPS et intranet
|
||||
|
||||
!!! tip "Avec Docker"
|
||||
Si tu préfères des conteneurs, `./docker/setup.sh vps|intranet` fait la même chose : voir [Docker Compose](docker.md).
|
||||
|
||||
Deux scripts font, **d'une seule commande**, tout ce qu'on ferait à la main. Ils se lancent **en root sur le serveur**,
|
||||
depuis un clone du dépôt (hors de `/root` et `/home`, par exemple `/opt/PyQuest`), sur **Debian ou Ubuntu**. Ils sont
|
||||
**idempotents** : après une interruption, on relance la même commande. `--dry-run` affiche tout ce qui serait fait sans
|
||||
|
||||
@@ -70,6 +70,7 @@ plugins:
|
||||
L'éditeur de niveaux: The level editor
|
||||
Déploiement: Deployment
|
||||
Les installateurs (VPS et intranet): The installers (VPS and intranet)
|
||||
Docker Compose (VPS et intranet): Docker Compose (VPS and intranet)
|
||||
Mise en service et exploitation: Going live and operations
|
||||
Architecture: Architecture
|
||||
Tests de validation: Validation tests
|
||||
@@ -89,6 +90,7 @@ nav:
|
||||
- Héberger:
|
||||
- Déploiement: host/deploy.md
|
||||
- Les installateurs (VPS et intranet): host/installers.md
|
||||
- Docker Compose (VPS et intranet): host/docker.md
|
||||
- Mise en service et exploitation: host/operations.md
|
||||
- Référence:
|
||||
- Architecture: reference/architecture.md
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
# en /etc/nginx/snippets/pyquest-author-headers.conf. Les zones de limitation (limit_req_zone : pyquest_sync, pyquest_login, pyquest_admin) sont dans le bloc http.
|
||||
# Host $http_host (et non $host) : conserve le port, que Django compare à l'en-tête Origin des formulaires.
|
||||
|
||||
# Redirections relatives (Location: /api/auth/login/…) : correctes derrière n'importe quel port ou proxy, sans que
|
||||
# nginx reconstruise une adresse absolue à partir de ses propres ports.
|
||||
absolute_redirect off;
|
||||
|
||||
# Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on
|
||||
# liste tout ce que l'application sert. Les scripts-modules exigent text/javascript.
|
||||
types {
|
||||
|
||||
Executable
+114
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
# Essai réel des compose Docker : construit les images, démarre la pile INTRANET (autorité interne, SQLite) et la pile VPS
|
||||
# (MariaDB, certificat provisoire : Let's Encrypt n'est pas joignable en test) sur des ports libres, interroge nginx en
|
||||
# HTTPS (curl ne fait confiance qu'à l'autorité de la pile), vérifie en-têtes d'isolation, éditeur protégé, administration,
|
||||
# fichiers statiques, sauvegardes, puis détruit tout (volumes compris). Dure quelques minutes la première fois.
|
||||
# Ignoré (code 0) si Docker n'est pas utilisable. Lancé par « make test-docker » (pas par « make ci »).
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
docker info >/dev/null 2>&1 || { echo "docker : démon indisponible, essai ignoré"; exit 0; }
|
||||
docker compose version >/dev/null 2>&1 || { echo "docker compose : absent, essai ignoré"; exit 0; }
|
||||
WORK="$(mktemp -d)"
|
||||
fail() { echo "ÉCHEC : $1" >&2; exit 1; }
|
||||
|
||||
free_port() { # premier port libre à partir de $1
|
||||
local port="$1"
|
||||
while ss -ltnH | awk '{print $4}' | grep -qE "[:.]${port}\$"; do port=$((port + 1)); done
|
||||
echo "${port}"
|
||||
}
|
||||
HTTP="$(free_port 18080)"; HTTPS="$(free_port 18443)"
|
||||
[[ "${HTTPS}" != "${HTTP}" ]] || HTTPS="$(free_port $((HTTP + 1)))"
|
||||
|
||||
declare -a COMPOSES=()
|
||||
cleanup() {
|
||||
for c in "${COMPOSES[@]}"; do eval "${c} down -v --remove-orphans" >/dev/null 2>&1 || true; done
|
||||
rm -rf "${WORK}" "${ROOT}/docker/.env.test-"*
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# Les fichiers d'environnement de l'essai ont un nom à part : ceux de l'utilisateur (docker/.env.vps, .env.intranet)
|
||||
# ne sont jamais touchés.
|
||||
secret="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"
|
||||
BACKUPS="${WORK}/backups"; mkdir -p "${BACKUPS}"
|
||||
|
||||
check_stack() { # nom curl-args... : vérifications communes une fois la pile démarrée
|
||||
local name="$1" host="$2"; shift 2
|
||||
local base="https://${host}:${HTTPS}" curl_args=("$@")
|
||||
c() { curl -s "${curl_args[@]}" "$@"; }
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/")" == 200 ]] || fail "${name} : la page d'accueil doit répondre 200"
|
||||
headers="$(c -I "${base}/" | tr -d '\r')"
|
||||
echo "${headers}" | grep -qi '^cross-origin-opener-policy: same-origin' || fail "${name} : COOP manquant"
|
||||
echo "${headers}" | grep -qi '^cross-origin-embedder-policy: require-corp' || fail "${name} : COEP manquant"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/vendor/pyodide/pyodide.asm.wasm")" == 200 ]] || fail "${name} : le moteur Python (wasm) doit être servi"
|
||||
[[ "$(c -I "${base}/vendor/pyodide/pyodide.asm.wasm" | tr -d '\r' | grep -ci 'content-type: application/wasm')" == 1 ]] || fail "${name} : type MIME wasm"
|
||||
code_loc="$(c -o /dev/null -w '%{http_code} %{redirect_url}' "${base}/author.html")"
|
||||
[[ "${code_loc}" == "302 "*"/api/auth/login/?next=/author.html" ]] || fail "${name} : author.html doit renvoyer vers la connexion (reçu : ${code_loc})"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/login/")" == 200 ]] || fail "${name} : page de connexion"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/check/")" == 404 ]] || fail "${name} : /api/auth/check/ doit rester interne"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/static/admin/css/base.css")" == 200 ]] || fail "${name} : fichiers statiques de l'administration (volume partagé)"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/admin/")" == 302 ]] || fail "${name} : administration protégée"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' "${base}/api/sync/")" == 404 ]] || fail "${name} : l'API de synchronisation doit joindre la base (404 attendu)"
|
||||
[[ "$(c -o /dev/null -w '%{http_code}' "http://${host}:${HTTP}/")" == 301 ]] || fail "${name} : HTTP doit rediriger vers HTTPS"
|
||||
}
|
||||
|
||||
# ---- intranet -----------------------------------------------------------------------------------------------------------
|
||||
ENVI="${ROOT}/docker/.env.test-intranet"
|
||||
cat > "${ENVI}" <<ENV
|
||||
PYQUEST_SECRET_KEY=${secret}
|
||||
PYQUEST_HOSTS=localhost,127.0.0.1
|
||||
PYQUEST_ORIGINS=https://localhost:${HTTPS},https://127.0.0.1:${HTTPS}
|
||||
PYQUEST_HTTP_PORT=${HTTP}
|
||||
PYQUEST_HTTPS_PORT=${HTTPS}
|
||||
PYQUEST_BACKUP_DIR=${BACKUPS}/intranet
|
||||
ENV
|
||||
mkdir -p "${BACKUPS}/intranet"
|
||||
DCI="docker compose -f ${ROOT}/docker/compose.intranet.yaml --env-file ${ENVI} -p pyquest-test-intranet"
|
||||
COMPOSES+=("${DCI}")
|
||||
$DCI up -d --build --wait --wait-timeout 300 web backup >/dev/null 2>&1 || { $DCI logs --tail 40 >&2; fail "la pile intranet ne démarre pas"; }
|
||||
$DCI cp web:/etc/pyquest/tls/ca.crt "${WORK}/ca.crt" >/dev/null 2>&1
|
||||
[[ -s "${WORK}/ca.crt" ]] || fail "l'autorité interne doit être créée au premier démarrage"
|
||||
check_stack intranet localhost --cacert "${WORK}/ca.crt"
|
||||
[[ "$(curl -s --cacert "${WORK}/ca.crt" -o /dev/null -w '%{http_code}' "https://127.0.0.1:${HTTPS}/")" == 200 ]] || fail "intranet : l'adresse IP doit être dans le certificat"
|
||||
curl -s -o /dev/null "https://localhost:${HTTPS}/" 2>/dev/null && fail "intranet : sans confiance dans l'autorité, la connexion doit être refusée"
|
||||
curl -s "http://localhost:${HTTP}/pyquest-ca.crt" | cmp -s - "${WORK}/ca.crt" || fail "intranet : /pyquest-ca.crt doit servir l'autorité"
|
||||
[[ "$($DCI exec -T backend sh -c 'for p in /proc/[0-9]*; do awk "/^Uid/{print \$2}" $p/status; done | sort -u | tr "\n" " "')" == *10001* ]] || fail "intranet : gunicorn doit tourner sans privilèges"
|
||||
$DCI exec -T -e DJANGO_SUPERUSER_PASSWORD="Essai-${secret:0:12}" backend python manage.py createsuperuser --noinput --username essai --email essai@example.org >/dev/null 2>&1 || fail "intranet : création de l'administrateur"
|
||||
for _ in $(seq 1 20); do ls "${BACKUPS}/intranet"/pyquest-*.sqlite.gz >/dev/null 2>&1 && break; sleep 1; done
|
||||
gunzip -c "$(ls "${BACKUPS}/intranet"/pyquest-*.sqlite.gz | head -n1)" | wc -c | grep -qvx 0 || fail "intranet : sauvegarde SQLite absente ou vide"
|
||||
# Un backend recréé (nouvelle adresse) ne doit pas obliger à redémarrer nginx.
|
||||
$DCI up -d --force-recreate --wait --wait-timeout 120 backend >/dev/null 2>&1
|
||||
sleep 2
|
||||
[[ "$(curl -s --cacert "${WORK}/ca.crt" -o /dev/null -w '%{http_code}' "https://localhost:${HTTPS}/api/auth/login/")" == 200 ]] || fail "intranet : nginx doit retrouver un backend recréé"
|
||||
# L'autorité survit à un arrêt/redémarrage (volume).
|
||||
$DCI down >/dev/null 2>&1
|
||||
$DCI up -d --wait --wait-timeout 120 web >/dev/null 2>&1
|
||||
$DCI cp web:/etc/pyquest/tls/ca.crt "${WORK}/ca2.crt" >/dev/null 2>&1
|
||||
cmp -s "${WORK}/ca.crt" "${WORK}/ca2.crt" || fail "intranet : l'autorité ne doit pas changer au redémarrage"
|
||||
$DCI down -v >/dev/null 2>&1
|
||||
|
||||
# ---- VPS (certificat provisoire) ------------------------------------------------------------------------------------------
|
||||
ENVV="${ROOT}/docker/.env.test-vps"
|
||||
cat > "${ENVV}" <<ENV
|
||||
PYQUEST_DOMAIN=localhost.example.org
|
||||
PYQUEST_EMAIL=essai@example.org
|
||||
PYQUEST_SECRET_KEY=${secret}
|
||||
PYQUEST_DB_PASSWORD=$(python3 -c 'import secrets; print(secrets.token_hex(16))')
|
||||
PYQUEST_HTTP_PORT=${HTTP}
|
||||
PYQUEST_HTTPS_PORT=${HTTPS}
|
||||
PYQUEST_ORIGIN_PORT=:${HTTPS}
|
||||
PYQUEST_BACKUP_DIR=${BACKUPS}/vps
|
||||
ENV
|
||||
mkdir -p "${BACKUPS}/vps"
|
||||
DCV="docker compose -f ${ROOT}/docker/compose.vps.yaml --env-file ${ENVV} -p pyquest-test-vps"
|
||||
COMPOSES+=("${DCV}")
|
||||
$DCV up -d --build --wait --wait-timeout 300 web >/dev/null 2>&1 || { $DCV logs --tail 40 >&2; fail "la pile VPS ne démarre pas"; }
|
||||
check_stack vps localhost.example.org -k --resolve "localhost.example.org:${HTTPS}:127.0.0.1" --resolve "localhost.example.org:${HTTP}:127.0.0.1"
|
||||
# Défi Let's Encrypt : le dossier du webroot est servi en HTTP, sans redirection.
|
||||
$DCV exec -T web sh -c 'mkdir -p /var/www/letsencrypt/.well-known/acme-challenge && echo challenge-ok > /var/www/letsencrypt/.well-known/acme-challenge/probe'
|
||||
[[ "$(curl -s --resolve "localhost.example.org:${HTTP}:127.0.0.1" "http://localhost.example.org:${HTTP}/.well-known/acme-challenge/probe")" == challenge-ok ]] || fail "vps : le défi ACME doit être servi en HTTP"
|
||||
$DCV exec -T db sh -c 'mariadb -u pyquest -p"$MARIADB_PASSWORD" pyquest -e "select count(*) from django_migrations" >/dev/null' || fail "vps : le backend doit avoir migré la base MariaDB"
|
||||
$DCV up -d --wait --wait-timeout 120 certbot backup >/dev/null 2>&1
|
||||
for _ in $(seq 1 20); do ls "${BACKUPS}/vps"/pyquest-*.sql.gz >/dev/null 2>&1 && break; sleep 1; done
|
||||
gunzip -c "$(ls "${BACKUPS}/vps"/pyquest-*.sql.gz | head -n1)" | grep -q "django_migrations" || fail "vps : sauvegarde MariaDB absente ou invalide"
|
||||
echo "docker : piles intranet et VPS ok"
|
||||
Reference in New Issue
Block a user