Aller au contenu

Déployer le registre de conteneurs Harbor sur Ubuntu 22.04 (prêt pour la production)

Monter Harbor sur Ubuntu 22.04 — installateur hors ligne Docker Compose, scan d'images Trivy, signature Notary, TLS Let's Encrypt, PostgreSQL en localhost, rotation des logs.

On vous demande de monter un registre de conteneurs privé. L’équipe a lancé le install.sh de Harbor contre un certificat auto-signé il y a deux ans et est passée à autre chose. Aujourd’hui, le certificat a expiré depuis quatre mois donc chaque docker pull avertit sur TLS, le PostgreSQL embarqué n’a jamais été sauvegardé parce que personne ne savait où il vivait, le volume du registre a dépassé 80 % du disque la semaine dernière et a commencé à 502 pendant les push, le scan d’images n’a jamais été activé, et les seules images signées dans le système sont celles du miroir public.

Ce qui se passe

Un déploiement Harbor réellement prêt pour la production demande plus que install.sh. Le nom d’hôte doit être un vrai FQDN avec un certificat Let’s Encrypt valide (les clients modernes refusent le HTTP nu pour push/pull v2) ; Trivy est activé à l’installation pour que chaque push reçoive un scan CVE ; Notary v1 est câblé si vous voulez des politiques d’images signées ; le PostgreSQL et Redis embarqués n’écoutent que sur le réseau interne Compose ; le volume de données vit sur un chemin que l’instantané au niveau VM couvre ; l’horaire de GC est activé ou le registre grossit jusqu’à remplir le disque ; et le mot de passe admin posé à l’installation est tourné immédiatement dans le gestionnaire de secrets. Harbor est lui-même une pile Compose — l’hôte a besoin d’unattended-upgrades et de rotation des logs en conséquence.

Comment vérifier

Après installation, les écouteurs doivent ressembler à ça :

ss -lntp | grep -E ':(80|443|4443)\b'
# 0.0.0.0:80    nginx-inside-harbor (redirection HTTP -> HTTPS)
# 0.0.0.0:443   nginx-inside-harbor (TLS)
# 0.0.0.0:4443  notary-server (signature d'images)

L’API v2 doit répondre 200 après authentification :

curl -fsS -u admin:CHANGEME https://harbor.example.com/v2/_catalog

Et un docker login suivi d’un push d’une petite image doit faire l’aller-retour proprement :

docker login harbor.example.com
docker pull alpine:3.20 && docker tag alpine:3.20 harbor.example.com/library/alpine:3.20
docker push harbor.example.com/library/alpine:3.20

Après le push, l’interface Harbor pour cette image doit montrer un résultat de scan Trivy en une minute ou deux ; si elle reste « Not Scanned » indéfiniment, l’adaptateur Trivy ne tourne pas.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-harbor-ubuntu22.sh, puis exécutez-le. Il tourne sur un hôte Ubuntu 22.04 frais : apt update, moteur Docker + plugin compose, unattended-upgrades, ajustement sysctl/descripteurs, durcissement SSH, un chemin de données sous /data, certbot standalone pour le FQDN, un téléchargement vérifié de l’installateur hors ligne Harbor, un harbor.yml généré avec Trivy et Notary activés, et une boucle d’attente pour l’endpoint v2 avant de déclarer la réussite.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Harbor clean host installer
### Harbor offline installer with Trivy and Notary enabled
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables unattended-upgrades for security
### Let's Encrypt via standalone certbot (port 80 free at install time)
### No local backups; assumes VM-level backup of /var/lib/harbor and /data

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${HARBOR_DOMAIN:?Set HARBOR_DOMAIN (e.g. harbor.example.com)}"
: "${LE_EMAIL:?Set LE_EMAIL}"

HARBOR_VERSION="${HARBOR_VERSION:-v2.11.1}"
HARBOR_ADMIN_PASSWORD="$(openssl rand -base64 24)"
HARBOR_DB_PASSWORD="$(openssl rand -hex 24)"
HARBOR_DATA_VOLUME="/data"
HARBOR_INSTALL_DIR="/opt/harbor"

echo
echo "========================================"
echo "Harbor Ubuntu 22.04 Setup"
echo "Domain: ${HARBOR_DOMAIN}"
echo "Version: ${HARBOR_VERSION}"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive

echo "==> Updating base OS"
apt-get update
apt-get -y upgrade
apt-get -y install \
  ca-certificates curl gnupg lsb-release \
  vim chrony fail2ban unattended-upgrades \
  iproute2 lsof tcpdump dnsutils tar gzip unzip jq

echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true

echo "==> Applying sysctl tuning"
cat > /etc/sysctl.d/99-harbor.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.overcommit_memory = 1
vm.max_map_count = 262144
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-harbor.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Hardening SSH"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart ssh

echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Enabling unattended-upgrades for security"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG

echo "==> Installing Docker engine and compose plugin"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
  gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
  https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" \
  > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

cat > /etc/docker/daemon.json <<'DOCKERJSON'
{
  "log-driver": "json-file",
  "log-opts": { "max-size": "100m", "max-file": "5" },
  "live-restore": true,
  "default-ulimits": { "nofile": { "Name": "nofile", "Hard": 64000, "Soft": 64000 } }
}
DOCKERJSON

systemctl enable --now docker
systemctl restart docker

echo "==> Preparing Harbor data dir at ${HARBOR_DATA_VOLUME}"
install -d -o root -g root -m 0755 "${HARBOR_DATA_VOLUME}"

echo "==> Installing certbot and obtaining cert (standalone, port 80 must be free)"
apt-get -y install certbot
certbot certonly --standalone \
  -d "${HARBOR_DOMAIN}" --email "${LE_EMAIL}" \
  --agree-tos --no-eff-email --non-interactive \
  --preferred-challenges http

CERT_LIVE_DIR="/etc/letsencrypt/live/${HARBOR_DOMAIN}"

if [[ ! -f "${CERT_LIVE_DIR}/fullchain.pem" ]]; then
  echo "Let's Encrypt did not deliver a cert at ${CERT_LIVE_DIR}"
  exit 1
fi

systemctl enable --now certbot.timer

echo "==> Downloading Harbor ${HARBOR_VERSION} offline installer"
install -d -m 0755 "${HARBOR_INSTALL_DIR}"
cd "${HARBOR_INSTALL_DIR}"

TARBALL="harbor-offline-installer-${HARBOR_VERSION}.tgz"
curl -fsSL -O "https://github.com/goharbor/harbor/releases/download/${HARBOR_VERSION}/${TARBALL}"
curl -fsSL -O "https://github.com/goharbor/harbor/releases/download/${HARBOR_VERSION}/${TARBALL}.asc"

# Verify signature with the Harbor signing key
curl -fsSL https://raw.githubusercontent.com/goharbor/harbor/main/KEYS | \
  gpg --import - 2>/dev/null || true
gpg --batch --verify "${TARBALL}.asc" "${TARBALL}" || \
  echo "WARNING: GPG verification did not complete; proceed only if you trust the download path."

tar xzf "${TARBALL}"
cd harbor

echo "==> Writing harbor.yml"
cat > harbor.yml <<HARBORYML
hostname: ${HARBOR_DOMAIN}

http:
  port: 80

https:
  port: 443
  certificate: ${CERT_LIVE_DIR}/fullchain.pem
  private_key: ${CERT_LIVE_DIR}/privkey.pem

external_url: https://${HARBOR_DOMAIN}

harbor_admin_password: ${HARBOR_ADMIN_PASSWORD}

database:
  password: ${HARBOR_DB_PASSWORD}
  max_idle_conns: 50
  max_open_conns: 500

data_volume: ${HARBOR_DATA_VOLUME}

trivy:
  ignore_unfixed: false
  skip_update: false
  insecure: false

jobservice:
  max_job_workers: 10

notification:
  webhook_job_max_retry: 3

log:
  level: info
  local:
    rotate_count: 50
    rotate_size: 200M
    location: /var/log/harbor

_version: 2.11.0

proxy:
  http_proxy:
  https_proxy:
  no_proxy:
  components:
    - core
    - jobservice
    - trivy

upload_purging:
  enabled: true
  age: 168h
  interval: 24h
  dryrun: false
HARBORYML

chmod 600 harbor.yml

echo "==> Running Harbor installer with Trivy and Notary"
./install.sh --with-trivy --with-notary

echo "==> Waiting for Harbor v2 API"
for i in {1..120}; do
  if curl -fsS -k "https://127.0.0.1/api/v2.0/health" >/dev/null 2>&1; then
    break
  fi
  sleep 2
done

if ! curl -fsS -k "https://127.0.0.1/api/v2.0/health" >/dev/null 2>&1; then
  echo "Harbor v2 API never answered"
  ( cd "${HARBOR_INSTALL_DIR}/harbor" && docker compose ps )
  exit 1
fi

echo "==> Installing systemd unit for Harbor"
cat > /etc/systemd/system/harbor.service <<UNIT
[Unit]
Description=Harbor (Compose)
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${HARBOR_INSTALL_DIR}/harbor
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
LimitNOFILE=64000

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable harbor

echo "==> Adding certbot deploy hook to re-copy cert into Harbor on renewal"
mkdir -p /etc/letsencrypt/renewal-hooks/deploy
cat > /etc/letsencrypt/renewal-hooks/deploy/harbor.sh <<HOOK
#!/usr/bin/env bash
set -euo pipefail
cd ${HARBOR_INSTALL_DIR}/harbor
docker compose down
./install.sh --with-trivy --with-notary
HOOK
chmod 700 /etc/letsencrypt/renewal-hooks/deploy/harbor.sh

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "Services:"
systemctl is-active docker harbor chrony fail2ban || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|4443)\b' || true
echo
echo "Harbor compose state:"
( cd "${HARBOR_INSTALL_DIR}/harbor" && docker compose ps )
echo
echo "Web UI:"
echo "https://${HARBOR_DOMAIN}/"
echo
echo "Admin credentials (rotate immediately after first login):"
echo "  user:     admin"
echo "  password: ${HARBOR_ADMIN_PASSWORD}"
echo
echo "Save the admin password and DB password (also in /opt/harbor/harbor/harbor.yml) to your secrets manager,"
echo "then chmod 600 the file and consider rotating both via the UI before the first push."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-harbor-ubuntu22.sh
HARBOR_DOMAIN=harbor.example.com LE_EMAIL=ops@example.com /root/setup-harbor-ubuntu22.sh

Le script génère un mot de passe admin aléatoire et l’imprime une fois à la fin — capturez-le dans votre gestionnaire de secrets, connectez-vous, tournez-le par l’interface, puis activez un horaire de GC sous Administration -> Garbage Collection (hebdomadaire convient pour la plupart des équipes) et une politique de scan de vulnérabilité sous Configuration -> Vulnerability. Les sauvegardes au niveau hôte sont hors périmètre : /data et /opt/harbor/harbor/harbor.yml sont les chemins avec état, et la VM est présumée avoir des instantanés/sauvegardes au niveau cloud.

Le registre de conteneurs est le bas de la chaîne d’approvisionnement — appariez Harbor avec la chaîne de déploiement qui pousse vers lui sur un environnement infogéré Stack Harbor : Hébergement cloud et PaaS →.