mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Docker on a VPS with a host firewall: DOCKER-USER script and documentation (iptables nft/legacy, ordering, systemd hook, ufw notes)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -64,6 +64,67 @@ $PQ down # stop (WITHOUT -v: "down -v" deletes t
|
||||
- **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.
|
||||
|
||||
## Host firewall (iptables, ufw)
|
||||
|
||||
Docker writes its own firewall rules (`DOCKER`, `DOCKER-USER` chains, address translation). A strict host firewall can
|
||||
break them. **Typical symptom**, as early as the build: `apk add` or `apt-get` print `DNS: transient error` or
|
||||
`Temporary failure resolving`, while the host itself reaches the Internet. The failures met on a real VPS (Debian,
|
||||
nginx and MariaDB already present, custom iptables firewall, `DROP` policies):
|
||||
|
||||
| Cause | How to recognise it | Remedy |
|
||||
|---|---|---|
|
||||
| The firewall script flushes all chains (`iptables -F`, `-X`, `-t nat -F`) **after** Docker started | `iptables -S DOCKER-USER`: "No chain/target/match by that name" | restart Docker **after** the firewall (see below) |
|
||||
| Two engines mixed: `iptables` on nftables, rules from Docker or another tool in legacy | `iptables -V` shows `(nf_tables)` and the "iptables-legacy tables present" message; compare `iptables-nft -S` and `iptables-legacy -S` | **a single engine**: the one holding the host firewall; do not switch lightly (you would lose the rules). Docker uses the engine of the `iptables` command |
|
||||
| `FORWARD` on `DROP` with nothing allowing containers | containers reach nothing (DNS included) | the `DOCKER-USER` rules below |
|
||||
| Rules written with `iptables -I` in the wrong order | a `DROP` for the public interface runs before the `ACCEPT ... ESTABLISHED`: replies from the Internet are dropped | write with `-A` on an emptied chain (the provided script does) |
|
||||
|
||||
### Setup (iptables)
|
||||
|
||||
The `docker/firewall/docker-user-rules.sh` script (tested on this VPS) sets up the `DOCKER-USER` chain, which Docker
|
||||
consults before its own rules: everything is accepted for containers and replies, **only the `PUBLIC_PORTS` (80 and
|
||||
443) are reachable from the Internet**, anything else arriving on the public interface is refused (without it, every
|
||||
port published by a container would be open to the world: Docker bypasses `INPUT` rules).
|
||||
|
||||
```bash
|
||||
install -m 755 docker/firewall/docker-user-rules.sh /usr/local/sbin/docker-user-rules.sh
|
||||
mkdir -p /etc/systemd/system/docker.service.d
|
||||
printf '[Service]\nExecStartPost=-/usr/local/sbin/docker-user-rules.sh\n' > /etc/systemd/system/docker.service.d/firewall.conf
|
||||
systemctl daemon-reload && systemctl restart docker
|
||||
iptables -S DOCKER-USER # the rules are there
|
||||
docker run --rm alpine apk add --no-cache bash # the container reaches the Internet
|
||||
```
|
||||
|
||||
- The **`-`** before the `ExecStartPost` path is essential: without it, a script error (missing or non-executable file:
|
||||
`status=203/EXEC`) stops Docker, hence every container on the machine.
|
||||
- Variables: `PUBLIC_PORTS="80 443 8883"` for other ports published by containers that must stay public;
|
||||
`TRUSTED_IFS="wg0"` to never filter a VPN. Put them in the unit (`Environment=` in the same `.conf`) rather than in the
|
||||
script.
|
||||
- **Order at boot**: the firewall must run **before** Docker (`Before=docker.service` in its service), or end with
|
||||
`systemctl is-active --quiet docker && systemctl restart docker`. For containers to survive that Docker restart, set
|
||||
`"live-restore": true` in `/etc/docker/daemon.json`.
|
||||
- Do **not** put these rules in the general firewall script: it empties the chains, so `DOCKER-USER` does not exist yet
|
||||
when they would run.
|
||||
- To open a test on other ports (`--http-port`, `--https-port`), add them to `PUBLIC_PORTS` for the duration of the
|
||||
test, or go through your VPN.
|
||||
- Also check that no general rule cancels the firewall: for example `iptables -I INPUT -m conntrack --ctstate
|
||||
NEW,ESTABLISHED -j ACCEPT` accepts **every** new inbound connection.
|
||||
|
||||
### ufw
|
||||
|
||||
*Not tried here; standard Docker guidance.* `ufw` does not filter ports published by Docker (`ufw allow/deny` rules do
|
||||
not apply to them): a published port is open even if `ufw` denies it. To control it, use the same `DOCKER-USER` chain (the
|
||||
script above works with `ufw`, which also uses `iptables`) or the `ufw-docker` project. If containers have no outbound
|
||||
access, set `DEFAULT_FORWARD_POLICY="ACCEPT"` in `/etc/default/ufw`, then `ufw reload`, and allow the traffic of `docker0`
|
||||
and the `br-…` networks.
|
||||
|
||||
### Other points specific to a VPS that already hosts something else
|
||||
|
||||
- **Ports 80 and 443**: a host nginx and the Docker stack cannot share them (`address already in use`). For a test, stop
|
||||
nginx; for lasting coexistence, use `--http-port`/`--https-port` behind another proxy, or the classic installation
|
||||
instead of Docker.
|
||||
- **Host MariaDB**: no conflict, the Docker stack's database is not published.
|
||||
- **Let's Encrypt**: port 80 must be reachable from the Internet (hence in `PUBLIC_PORTS`).
|
||||
|
||||
## Verified
|
||||
|
||||
`make test-docker` builds the images, starts both stacks on free ports, queries nginx over HTTPS (isolation headers,
|
||||
|
||||
@@ -65,6 +65,67 @@ $PQ down # arrêt (SANS -v : « down -v » suppr
|
||||
- **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.
|
||||
|
||||
## Pare-feu de l'hôte (iptables, ufw)
|
||||
|
||||
Docker écrit lui-même ses règles de pare-feu (chaînes `DOCKER`, `DOCKER-USER`, traduction d'adresse). Un pare-feu
|
||||
d'hôte strict peut les casser. **Symptôme typique**, dès la construction : `apk add` ou `apt-get` affichent
|
||||
`DNS: transient error` ou `Temporary failure resolving`, alors que l'hôte accède à Internet. Les pannes rencontrées
|
||||
sur un VPS réel (Debian, nginx et MariaDB déjà présents, pare-feu iptables maison, politiques `DROP`) :
|
||||
|
||||
| Cause | Comment la reconnaître | Remède |
|
||||
|---|---|---|
|
||||
| Le script de pare-feu vide toutes les chaînes (`iptables -F`, `-X`, `-t nat -F`) **après** le démarrage de Docker | `iptables -S DOCKER-USER` : « No chain/target/match by that name » | relancer Docker **après** le pare-feu (voir ci-dessous) |
|
||||
| Deux moteurs mélangés : `iptables` en nftables, règles de Docker ou d'un autre outil en legacy | `iptables -V` affiche `(nf_tables)` et le message « iptables-legacy tables present » ; comparer `iptables-nft -S` et `iptables-legacy -S` | **un seul moteur** : celui qui contient le pare-feu de l'hôte ; ne pas basculer à la légère (on perdrait les règles). Docker utilise le moteur de la commande `iptables` |
|
||||
| `FORWARD` en `DROP` sans autorisation pour les conteneurs | les conteneurs n'atteignent rien (DNS inclus) | règles `DOCKER-USER` ci-dessous |
|
||||
| Règles écrites avec `iptables -I` dans le mauvais ordre | un `DROP` de l'interface publique passe avant les `ACCEPT ... ESTABLISHED` : les réponses d'Internet sont jetées | écrire avec `-A` sur une chaîne vidée (le script fourni le fait) |
|
||||
|
||||
### Mise en place (iptables)
|
||||
|
||||
Le script `docker/firewall/docker-user-rules.sh` (testé sur ce VPS) règle la chaîne `DOCKER-USER`, que Docker consulte avant
|
||||
ses propres règles : tout est accepté pour les conteneurs et les réponses, **seuls les ports de `PUBLIC_PORTS`
|
||||
(80 et 443) sont joignables depuis Internet**, le reste venant de l'interface publique est refusé (sans cela, tout
|
||||
port publié par un conteneur serait ouvert au monde : Docker contourne les règles `INPUT`).
|
||||
|
||||
```bash
|
||||
install -m 755 docker/firewall/docker-user-rules.sh /usr/local/sbin/docker-user-rules.sh
|
||||
mkdir -p /etc/systemd/system/docker.service.d
|
||||
printf '[Service]\nExecStartPost=-/usr/local/sbin/docker-user-rules.sh\n' > /etc/systemd/system/docker.service.d/firewall.conf
|
||||
systemctl daemon-reload && systemctl restart docker
|
||||
iptables -S DOCKER-USER # les règles sont là
|
||||
docker run --rm alpine apk add --no-cache bash # le conteneur sort sur Internet
|
||||
```
|
||||
|
||||
- Le **`-`** devant le chemin d'`ExecStartPost` est essentiel : sans lui, une erreur du script (fichier absent ou non
|
||||
exécutable : `status=203/EXEC`) arrête Docker, donc tous les conteneurs de la machine.
|
||||
- Variables : `PUBLIC_PORTS="80 443 8883"` pour d'autres ports publiés par des conteneurs qui doivent rester publics ;
|
||||
`TRUSTED_IFS="wg0"` pour ne jamais filtrer un VPN. Mets-les dans l'unité (`Environment=` du même fichier `.conf`) plutôt
|
||||
que dans le script.
|
||||
- **Ordre au démarrage de la machine** : le pare-feu doit s'exécuter **avant** Docker (`Before=docker.service` dans son
|
||||
service), ou se terminer par `systemctl is-active --quiet docker && systemctl restart docker`. Pour que les conteneurs
|
||||
survivent à ce redémarrage de Docker, active `"live-restore": true` dans `/etc/docker/daemon.json`.
|
||||
- Ne place **pas** ces règles dans le script général du pare-feu : il vide les chaînes, donc `DOCKER-USER` n'existe pas
|
||||
encore au moment où elles s'exécuteraient.
|
||||
- Pour ouvrir un test sur d'autres ports (`--http-port`, `--https-port`), ajoute-les à `PUBLIC_PORTS` le temps de
|
||||
l'essai, ou passe par ton VPN.
|
||||
- Vérifie aussi qu'aucune règle générale n'annule le pare-feu : par exemple `iptables -I INPUT -m conntrack --ctstate
|
||||
NEW,ESTABLISHED -j ACCEPT` accepte **toute** nouvelle connexion entrante.
|
||||
|
||||
### ufw
|
||||
|
||||
*Non essayé ici ; consignes standard de Docker.* `ufw` ne filtre pas les ports publiés par Docker (les règles
|
||||
`ufw allow/deny` ne s'y appliquent pas) : un port publié est ouvert même si `ufw` le refuse. Pour le contrôler, utilise
|
||||
la même chaîne `DOCKER-USER` (le script ci-dessus fonctionne avec `ufw`, qui utilise aussi `iptables`) ou le projet
|
||||
`ufw-docker`. Si les conteneurs n'ont pas de sortie, mets `DEFAULT_FORWARD_POLICY="ACCEPT"` dans `/etc/default/ufw`, puis
|
||||
`ufw reload`, et autorise le trafic de `docker0` et des réseaux `br-…`.
|
||||
|
||||
### Autres points propres à un VPS qui héberge déjà autre chose
|
||||
|
||||
- **Ports 80 et 443** : un nginx sur l'hôte et la pile Docker ne peuvent pas les partager (`address already in use`).
|
||||
Pour un essai, arrêter nginx ; pour une cohabitation durable, utiliser `--http-port`/`--https-port` derrière un autre
|
||||
proxy, ou l'installation classique plutôt que Docker.
|
||||
- **MariaDB de l'hôte** : sans conflit, la base de la pile Docker n'est pas publiée.
|
||||
- **Let's Encrypt** : le port 80 doit être joignable depuis Internet (donc dans `PUBLIC_PORTS`).
|
||||
|
||||
## Vérifié
|
||||
|
||||
`make test-docker` construit les images, démarre les deux piles sur des ports libres, interroge nginx en HTTPS (en-têtes
|
||||
|
||||
Reference in New Issue
Block a user