Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Harbor Deep Dive: Storage Internals, GC Pitfalls, Scanning & Production Hardening
Operations 87 min read

Harbor Deep Dive: Storage Internals, GC Pitfalls, Scanning & Production Hardening

This comprehensive guide dissects Harbor's content-addressable storage (manifest vs blob), explains why deleting tags doesn't reclaim space, details the 7-component architecture, push/pull mechanics, and provides production-grade configs for nginx, core, registry, and Trivy. It includes troubleshooting playbooks for GC failures, 413 errors, and silent scan misses, plus monitoring alerts, a healthcheck script, and rollback strategies.

1. Content-Addressable Storage: Why Deleted Tags Don't Free Space

Harbor (OCI registry) has no "image" object—only manifest (index) and blob (content). A tag points to a manifest; a manifest references multiple blobs. Blobs are globally shared across the entire registry.

Dockerfile build output
  |
  v
manifest (application/vnd.oci.image.manifest.v1+json)
  |  config:  sha256:aa11... (image config JSON, few KB)
  |  layers:
  |   - sha256:bb22... (base layer ubuntu:24.04)
  |   - sha256:cc33... (apt install layer)
  |   - sha256:dd44... (app code layer)
  v
blob store (content-addressed, path = /blobs/sha256/<first2>/<full-digest>)
  |
  +--> referenced by tag v1.0.0
  +--> referenced by tag v1.0.1   (same base layer, no duplicate space)
  +--> referenced by 12 other projects

Three counter-intuitive conclusions:

Same base layer stored once physically. 100 images using ubuntu:24.04 base: the 78 MB counts once.

Deleting a tag ≠ deleting blobs. Tag is just a pointer to manifest; manifest points to blobs. Deleting the pointer doesn't reclaim content.

Blob reclamation requires GC, and GC only deletes blobs with zero manifest references . Manifests themselves are never deleted by GC, so they accumulate monotonically.

A project building 50×/day with 30-day retention accumulates 1,500 manifests (each few hundred bytes to KB), slowing DB and storage indexes.

1.2 Seven Containers, Seven Failure Domains

Harbor 2.x is a multi-container architecture; each component fails differently. Mixing logs is the least efficient troubleshooting method.

client docker push / pull
                    |
                    v
    +-------------------------+
    | nginx (443, TLS term)   |
    | client_max_body_size 0  |
    +------------+------------+
                 |
         +-------+-------+
         |               |
         v               v
   +-----------+   +---------------+
   | portal    |   | core (API)    |
   | :8080     |   | :8080         |
   | frontend  |   | auth/project  |
   +-----------+   | quota/tag/audit|
                   +-------+-------+
                           |
            +----------------+----------------+
            |                |                |
            v                v                v
       +---------+      +-------------+  +-----------+
       | registry|      | jobservice  |  | trivy     |
       | :5000   |      | :8080       |  | adapter   |
       | blob R/W|      | GC/replicate|  | :8080     |
       +----+----+      +------+------+  +-----+-----+
            |                |                |
            v                v                v
       +---------+      +-------------+  +-----------+
       | S3/local|      | PostgreSQL  |  | trivy-db  |
       | blob    |      | redis       |  | (offline) |
       +---------+      +-------------+  +-----------+

Component responsibilities and failure boundaries:

nginx : TLS termination + reverse proxy. Must set client_max_body_size 0 or large layers get 413.

core : Single API entry. Auth, projects, quotas, tags, audit. If down, pull may work (depends on auth), push always fails.

registry : Actual blob read/write (CNCF distribution). Only component touching storage directly.

jobservice : Async task executor. GC, replication, scanning, retention policies queue here. Worker count determines scan throughput.

trivy adapter : Translates Harbor scan requests to Trivy calls. Does not bundle vulnerability DB; DB must be updated separately.

postgres / redis : Metadata + cache. Harbor 2.8+ supports external PG; production must use external instance.

exporter : Prometheus metrics at :8080/metrics.

Diagnostic rule: push fails → check nginx & core; pull fails → check registry & storage; scan stuck → check jobservice & trivy adapter. Three independent paths, separate logs.

1.3 Push Four Round-Trips: Where Latency Lives

docker push

is not a single upload; it's negotiate → chunk → commit in four phases:

1) HEAD /v2/<repo>/blobs/sha256:<digest>
   exists → skip layer (all deduplication value here)
   |
2) POST /v2/<repo>/blobs/uploads/ → 202 + Location
   |
3) PATCH <Location> (chunked, default 5 MB)
   Content-Range: 0-5242879
   |
4) PUT <Location>?digest=sha256:<digest> → 201 commit
   |
5) PUT /v2/<repo>/manifests/<tag>

Step 1 is the overlooked performance key: if blob exists, push takes seconds. That's why pushing the same base image again is fast.

Steps 2–3 transfer data. Critical detail: registry blob upload is a temporary session. If interrupted, a residual file remains in blobupload dir until retry or registry restart.

Step 4 PUT ?digest= is verification commit . Registry recomputes full blob SHA-256 and compares with URL digest; mismatch returns DIGEST_INVALID. This step scales linearly with layer size and cannot be parallelized via chunking because verification requires complete content. Hence a 2 GB layer adds several seconds of CPU hashing even on 10 GbE—this is the real cause of "push shows 100% then hangs", not network slowness.

1.4 Why Deleting Tags Doesn't Free Space: Unidirectional References

Reference chain is one-way: tag → manifest → blob. Reverse does not hold; blobs don't know who references them.

Before delete
 tag:v1.0.0 --> manifest:M1 --> blob:A, blob:B
 tag:v1.0.1 --> manifest:M2 --> blob:A, blob:C

Execute delete tag v1.0.0
 tag:v1.0.0 gone, M1 becomes dangling manifest
 M1 still exists, still references blob:B

Run GC
 M1 never explicitly deleted → GC thinks it "might be referenced"
   Actual behavior: GC only deletes blobs with zero manifest references
   As long as M1 exists, blob:B won't be deleted

This explains the common phenomenon: delete tag, run GC, space barely drops. Dangling manifests still protect their layers.

Harbor 2.10+ added --delete-untagged GC option: "delete all manifests without tags, then reclaim their exclusively-owned blobs". In 2.15 extended to delete by tag name then GC in one step.

Warning: --delete-untagged removes all untagged artifacts, including those referenced by digest ( image@sha256:...). If anyone pins versions via digest, enabling this breaks their pulls with manifest unknown.

1.5 Quota, Retention, Tag Immutability: Three Locks, Different Scopes

Project Quota : Target = Storage bytes; Trigger = On push; Over-limit Action = Reject push

Retention Policy : Target = Tags; Trigger = Scheduled job; Over-limit Action = Delete tags

Tag Immutability : Target = Tag rename/overwrite; Trigger = On push; Over-limit Action = Reject overwrite

Quota is per-project, counted via quota_usage table: only project-exclusive blobs + shared blobs pro-rated by reference count . This pro-rating causes "mysterious" quota spikes: a 100 MB base layer shared by 5 projects → each accounts 20 MB. Delete 4 projects, the remaining project's usage jumps from 20 MB to 100 MB.

Retention policy's trap is its time basis : default uses push time, not tag creation time. Someone does docker tag on old image, pushes new tag → image's "last push time" refreshes, so images that should be cleaned stay.

Tag immutability is a hard rule; once enabled even admin cannot overwrite. Real value: prevent silent latest overwrite —but CI pipelines must switch from "push same tag every build" to "tag with git SHA".

2. Production Baseline: Four-Layer Config from nginx to Storage Backend

2.1 Baseline Assumptions: Three Things Determine Harbor's Ceiling

+----------------+  +----------------+  +----------------+
| harbor-01      |  | harbor-02      |  | harbor-03      |
| 172.20.12.21   |  | 172.20.12.22   |  | 172.20.12.23   |
| 16C / 64G      |  | 16C / 64G      |  | 16C / 64G      |
| nginx+core+reg |  | nginx+core+reg |  | nginx+core+reg |
+--------+-------+  +--------+-------+  +--------+-------+
         |                |                |
         |    10GbE 172.20.12.0/24        |
         +---------------------+---------------------+
                               |
                    +----------------------+----------------------+
                    |                      |                      |
                    v                      v                      v
             +---------------+      +-----------------+   +---------------+
             | minio x4      |      | postgres 16     |   | redis 7       |
             | 172.20.12.31- |      | 172.20.12.41    |   | 172.20.12.51  |
             | 34  S3 :9000  |      | primary + 1 replica|   | sentinel x3   |
             +---------------+      +-----------------+   +---------------+

Three ceiling determinants:

Blob storage write bandwidth : S3/MinIO 4 nodes, 10 GbE, raw ~1.1 GB/s. Push throughput ceiling.

PostgreSQL write capacity : Each push writes blob, artifact, tag, accessory tables. PG IOPS limits concurrent pushes.

jobservice worker count : Scanning & replication are async tasks; workers determine queue drain rate.

Most likely bottleneck: PG , because its writes are serial row-lock contention , unlike storage which scales linearly by adding nodes.

2.2 nginx Layer: Three Params Decide Push Success

Harbor's nginx template handles most cases, but production almost always needs three changes.

# /etc/harbor/nginx/nginx.conf (container /etc/nginx/nginx.conf)
worker_processes auto;
worker_rlimit_nofile 65535;

events {
  worker_connections 8192;
  multi_accept on;
}

http {
  client_max_body_size 0;          # MUST be 0, else large layer 413
  client_body_buffer_size 1m;      # small layers in memory, avoid temp file
  proxy_request_buffering off;     # stream forward, no disk spill
  proxy_buffering off;             # response not buffered, pull won't stall
  keepalive_timeout 300s;
  keepalive_requests 10000;
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;

  upstream harbor_core {
    server 127.0.0.1:8080;
    keepalive 64;
  }
  upstream harbor_registry {
    server 127.0.0.1:5000;
    keepalive 64;
  }
}

Four params' cause-effect:

client_max_body_size 0 = unlimited. Default 1m → returns 413 Request Entity Too Large. In docker push shows received unexpected HTTP status: 413, often mistaken for quota limit.

proxy_request_buffering off = performance critical. If on, nginx writes entire request body to temp file then forwards to registry. A 2 GB layer = "write 2 GB disk, read 2 GB forward" → disk becomes bottleneck.

proxy_buffering off affects pull. If on, nginx buffers response; large layer pull stalls then bursts, client sees "progress bar frozen".

worker_rlimit_nofile must exceed worker_connections x 2. Default 1024/512 combo hits worker_connections are not enough at hundreds of concurrent pulls.

Verify nginx actually reloaded:

docker exec -it nginx nginx -t
docker exec -it nginx nginx -s reload
docker exec -it nginx nginx -T 2>/dev/null \
  | grep -E 'client_max_body|request_buffering'
nginx: configuration file /etc/nginx/nginx.conf
     test is successful

     client_max_body_size 0;
     proxy_request_buffering off;
<-- [judgment] If second block has no output, you edited the wrong file. Harbor's nginx config lives in the image; must mount override.

2.3 core Layer: DB Connection Pool & Session Two Pitfalls

Core config in harbor.yml, change → ./prepare re-render → docker compose up -d.

# harbor.yml key section
database:
  type: external
  external:
    host: 172.20.12.41
    port: 5432
    username: harbor
    password: !secret
    sslmode: require
    max_idle_conns: 50
    max_open_conns: 300
    conn_max_lifetime: 5m
    conn_max_idle_time: 2m

core:
  secret: !secret
  quota_update_provider: db

jobservice:
  max_job_workers: 20
  max_worker: 20
  job_loggers:
    - STD_OUTPUT
  logger_sweeper_duration: 1
max_open_conns: 300

math: 3 core replicas x 300 = 900 connections + jobservice + exporter → PG max_connections must be ≥ 1000. Each PG connection ~10 MB shared memory + backend overhead; 1000 connections ≈ 10 GB, confirm instance memory suffices.

Classic coupling: Only raising Harbor's max_open_conns without PG's max_connections → push peak yields FATAL: sorry, too many clients already, while Harbor only logs failed to ping database.

# postgresql.conf matching adjustments
max_connections = 1200
shared_buffers = 8GB          # 25% RAM
effective_cache_size = 24GB   # 75% RAM
work_mem = 16MB
maintenance_work_mem = 1GB
wal_compression = on
checkpoint_completion_target = 0.9
random_page_cost = 1.1        # SSD must lower; default 4.0 misleads optimizer
random_page_cost = 1.1</strong> is mandatory on SSD. Default 4.0 assumes spinning disks, makes optimizer prefer seq scans over index scans. Harbor's <code>artifact

table at hundreds of thousands of rows: this param directly impacts tag query latency.

# Verify connection count & usage
psql -h 172.20.12.41 -U harbor -d registry -c \
"SELECT count(*) AS used, current_setting('max_connections') AS max FROM pg_stat_activity;"
psql -h 172.20.12.41 -U harbor -d registry -c \
"SELECT state, count(*) FROM pg_stat_activity GROUP BY state;"
used |  max
------+------
  312 | 1200

 state   | count
---------+-------
 active  |    18
 idle    |   289
 idle in transaction | 5
<-- [critical anomaly] "idle in transaction" 5 is danger signal. Held row locks block GC deletes; >30 min must investigate source.

2.4 registry Layer: Storage Driver Three Must-Change Items

Registry is the only component directly touching blob storage; misconfig → push succeeds but pull fails.

# registry config (Harbor renders to /etc/registry/config.yml)
storage:
  s3:
    accesskey: !secret
    secretkey: !secret
    region: us-east-1
    regionendpoint: http://172.20.12.31:9000
    bucket: harbor-blobs
    rootdirectory: /registry
    secure: false
    v4auth: true
    chunksize: 5242880          # 5 MB, aligns with docker chunk size
    multipartcopychunksize: 33554432
    multipartcopymaxconcurrency: 100
    multipartcopythresholdsize: 33554432
    forcepathstyle: true
    delete:
      enabled: true             # GC prerequisite
    cache:
      blobdescriptor: redis
    maintenance:
      uploadpurging:
        enabled: true
        age: 168h               # 7 days, clean residual upload sessions
        interval: 24h

Three must-change items explained:

delete.enabled: true = GC prerequisite. Default false → registry DELETE API returns 405, Harbor GC gets no deletable list → "GC reports success but deleted nothing".

chunksize aligned with docker chunking . Docker defaults 5 MB/chunk; if set to 10 MB, S3 multipart upload does secondary split, extra memory copy.

uploadpurging.age: 168h cleans interrupted push residuals. These don't count in quota (not in blob table) but consume S3 storage and are invisible to GC. Common cause of "storage bill vs Harbor usage mismatch".

Storage layer four-dimensional breakdown:

① Must-change items

Parameter: delete.enabled; Location: registry storage; Note: Without it GC ineffective

Parameter: bucket / rootdirectory; Location: registry storage; Note: Point to correct bucket & prefix

Parameter: regionendpoint; Location: registry storage; Note: MinIO must be explicit

Parameter: forcepathstyle; Location: registry storage; Note: MinIO must be true

② Coupling items chunksize with client chunk size. uploadpurging.age > longest single push duration, else in-flight session purged. max_open_conns vs PG max_connections ratio. max_job_workers vs PG pool: each worker consumes 1 connection.

③ Performance items (formula-driven)

jobservice worker count:

max_job_workers = min( CPU cores x 2 , PG remaining connections / 2 )
                = min( 16 x 2 , (1200 - 900) / 2 )
                = min( 32 , 150 )
                = 32

Chosen 20 not 32 because scan tasks are CPU-intensive (Trivy unpacks layers + matches); 20 concurrent scans saturate 16 cores, more just queues.

S3 capacity planning:

Actual needed = deduped total x 1.3 (manifest + index overhead)
              x 1.15 (upload residual peak)
planning = deduped total x 1.5

④ Forbidden red lines

Parameter: rootdirectory change; Consequence: All old blobs orphaned

Parameter: bucket change; Consequence: Same as above, equals wiping registry

Parameter: delete.enabled off; Consequence: GC impossible, monotonic growth

Parameter: v4auth off; Consequence: MinIO some versions reject signature rootdirectory is absolute minefield. Changing it doesn't migrate data; registry looks in new dir → all images manifest unknown. Migration requires regctl or skopeo image-level copy.

2.5 OS & Container Layer: Three Kernel Param Groups + One systemd Limit

Harbor runs in containers but bottlenecks often in host kernel.

# /etc/sysctl.d/90-harbor.conf
net.core.somaxconn = 32768
net.ipv4.tcp_max_syn_backlog = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.ip_local_port_range = 10000 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_slow_start_after_idle = 0
fs.file-max = 2097152
vm.max_map_count = 262144
tcp_slow_start_after_idle = 0</strong> critical for registries. Docker client often "push layer, pause seconds, push next"; if enabled, congestion window resets to initial after idle, throughput degrades to sawtooth.</p><p><code>vm.max_map_count</strong> for Trivy: it mmaps many files when unpacking tar layers; default 65530 causes <code>Out of memory mapping

on large images.

Docker daemon fd & log must be set:

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "5"
  },
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 1048576,
      "Soft": 1048576
    }
  },
  "data-root": "/data/docker",
  "live-restore": true
}
max-size: 100m

+ max-file: 5 mandatory. Jobservice scan failures spew huge error logs; unbounded → one container fills /var/lib/docker → cascades all containers fail to start.

Real failure chain worth remembering: logs fill disk → docker daemon can't create containers → Harbor core restart fails → entire registry down. Root cause: logs; symptom: storage failure.

# Verify config effective
docker info --format '{{.LoggingDriver}} {{.DockerRootDir}}'
docker info --format '{{json .RegistryConfig.Mirrors}}'
DPID=$(pgrep -f dockerd | head -1)
grep 'open files' /proc/${DPID}/limits
json-file /data/docker
null
Max open files   1048576   1048576   files
<-- [judgment] If mirrors non-empty, mirror acceleration configured. Production Harbor nodes should NOT have mirrors; interferes with local registry pull path.

2.6 Trivy Scan Layer: Offline DB & Three Timeouts

Scanning is enterprise registry's core value, also most misconfigured. Core conflict: Trivy needs internet to update vuln DB, but production Harbor usually air-gapped.

# harbor.yml trivy section
trivy:
  ignore_unfixed: false
  skip_update: true          # air-gapped must be true
  offline_scan: true
  insecure: false
  timeout: 10m0s
  git_hub_token: ""
  skip_java_db_update: true
  db_repository: ""
  java_db_repository: ""

Three timeouts decide if scan "stucks":

timeout: 10m0s = single scan ceiling. Default 5 min insufficient for >2 GB images.

jobservice max_job_workers = concurrent scan count.

core scan_all_policy = periodic full rescan; if set, silently saturates CPU at business peak.

Offline DB update must be scripted; manual updates always forgotten:

# On internet-connected machine download offline DB
trivy image --download-db-only --cache-dir /tmp/trivy-db
trivy image --download-java-db-only --cache-dir /tmp/trivy-db
ls -lh /tmp/trivy-db/db/trivy.db
ls -lh /tmp/trivy-db/java-db/trivy-java.db
68M  Nov 23 06:12  /tmp/trivy-db/db/trivy.db
41M  Nov 23 06:12  /tmp/trivy-db/java-db/trivy-java.db
<-- [judgment] trivy.db ~60-70 MB normal. If only few MB, download truncated → scan returns 0 vulns false result.
# Copy to Harbor nodes & replace
install -d /data/harbor/trivy-adapter/trivy/db
install -m 644 /tmp/trivy-db/db/trivy.db \
  /data/harbor/trivy-adapter/trivy/db/trivy.db
install -m 644 /tmp/trivy-db/java-db/trivy-java.db \
  /data/harbor/trivy-adapter/trivy/java-db/trivy-java.db
docker restart trivy-adapter

Must verify adapter loaded DB, else it silently scans with empty DB:

docker logs trivy-adapter --tail=20 2>&1 \
  | grep -iE 'db|version|loaded'
T06:20:11Z [INFO] Loading DB from
     /home/scanner/.cache/trivy/db/trivy.db
T06:20:11Z [INFO] DB Version: 2
T06:20:12Z [INFO] Vulnerability DB is up to date
T06:20:12Z [INFO] Java DB is up to date

&lt;-- [judgment] "Vulnerability DB is up to date" prints even with skip_update=true; only means local DB usable, not latest. Check DB Version &amp; file mtime for freshness. Counter-intuitive point: skip_update: true makes Trivy NOT report "DB stale"; it scans with old DB normally. Offline scan results drift over time; must schedule DB updates and monitor trivy.db mtime.

3. High-Frequency Commands & Monitoring: Quantify "Registry Slow"

3.1 Five Commands to Separate Registry vs Client Issues

Pull slowness first blamed on registry; half the time it's client disk or network.

# 1) Client side: separate network vs disk time
time docker pull registry.example.com/payment/api:v1.2.3
# 2) See data volume (not image size)
docker history registry.example.com/payment/api:v1.2.3 \
  --format '{{.Size}}\t{{.CreatedBy}}' | head -10
# 3) Server side: registry request latency distribution
docker logs registry --tail=200 2>&1 \
  | grep -E 'GET|PUT' | tail -20
# 4) Reverse proxy: is it buffering?
docker exec nginx tail -50 /var/log/nginx/access.log
# 5) Storage side: S3 request latency
docker logs registry --tail=500 2>&1 | grep -c 'SlowRequest'
real    0m18.412s
user    0m0.421s
sys     0m3.118s

SIZE     CREATED BY
78.1MB   /bin/sh -c #(nop) ADD file:3d5f... in /
142MB    /bin/sh -c apt-get update && apt-get install
1.2MB    COPY ./app /app

&lt;-- [judgment] real 18.4s but user+sys only 3.5s → time spent waiting network or disk. If sys high, local unpack slow.

172.20.11.5 - - [23/Nov/2026:14:22:01 +0800]
  "GET /v2/payment/api/blobs/sha256:bb22... HTTP/1.1"
  200 81878016 "-" "docker/27.3.1" 3.218
172.20.11.5 - - [23/Nov/2026:14:22:04 +0800]
  "GET /v2/payment/api/blobs/sha256:cc33... HTTP/1.1"
  200 148897792 "-" "docker/27.3.1" 12.884

&lt;-- [critical anomaly] 148 MB took 12.9 s → 11.5 MB/s, far below 10 GbE 1.1 GB/s. Not bandwidth; single connection throttled or S3 serial read. Diagnosis order matters: first client real vs user+sys delta, then server access log $request_time . Former large → waiting network; latter large → server slow. Both normal but user feels slow → path between client and server.

3.2 Six One-Liners: Quota, GC, Dangling Manifests, Scan Status

Daily ops highest-frequency actions, each with clear judgment thresholds.

# 1) Project quota usage (find near-full projects)
curl -s -u "admin:${HARBOR_PASS}" \
  "https://registry.example.com/api/v2.0/quotas?page_size=100" \
  | jq -r '.quotas[] | select(.ref.id>0) | "\(.ref.name)\t\(.used.resource)/\(.hard.resource)"'
payment    42949672960/107374182400
search     98566144000/107374182400
infra      1073741824/10737418240

&lt;-- [critical anomaly] search project 91.8% used. Quota is hard limit; at 100% push gets 403, no auto-expand.

# 2) GC history & status
curl -s -u "admin:${HARBOR_PASS}" \
  "https://registry.example.com/api/v2.0/system/gc" \
  | jq -r '.items[-5:][] | "\(.create_time) \(.job_status) \(.parameters)"'
2026-11-20T02:00:11Z Success {"delete_untagged":true}
2026-11-21T02:00:09Z Success {"delete_untagged":true}
2026-11-22T02:00:13Z Success {"delete_untagged":false}

&lt;-- [critical anomaly] Third run delete_untagged=false → this GC won't delete dangling manifests, space won't shrink. Check who changed schedule.

# 3) Find dangling manifests (no tag ref)
H=${H:-https://registry.example.com}
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories/api/artifacts
?page_size=100&with_tag=false" \
  | jq -r '.tags == null | select(. == true)' | wc -l
# 4) Scan status summary: how many images never scanned
H=${H:-https://registry.example.com}
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories/api/
artifacts?page_size=100&with_scan_overview=true" \
  | jq -r '[.[]? | select(.scan_overview==null)] | length'
37

&lt;-- [critical anomaly] 37 artifacts lack scan_overview → never scanned. If scan_on_push enabled but still like this, jobservice queue blocked.

# 5) Critical vuln list (release gate)
cosign verify --key cosign.pub \
  registry.example.com/payment/api:v1.2.3 2>&1 | head -5
trivy image --severity CRITICAL,HIGH --ignore-unfixed \
  registry.example.com/payment/api:v1.2.3
registry.example.com/payment/api:v1.2.3 (debian 12.7)
Total: 2 (HIGH: 2, CRITICAL: 0)

+---------+------------------+----------+-------------------+
| LIBRARY | VULNERABILITY    | SEVERITY | FIXED VERSION     |
+---------+------------------+----------+-------------------+
| libssl3 | CVE-2026-1234    | HIGH     | 3.0.14-1~deb12u2  |
| zlib1g  | CVE-2026-5678    | HIGH     | 1:1.2.13.dfsg-1   |
+---------+------------------+----------+-------------------+

&lt;-- [judgment] Both have FIXED VERSION → "fixable but not fixed". If FIXED VERSION empty, upstream no patch yet; must accept or rebase.

# 6) Replication backlog (multi-cluster)
H=${H:-https://registry.example.com}
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/replication/executions?page_size=20" \
  | jq -r '.items[] | select(.status=="InProgress") | "\(.id) \(.trigger) \(.start_time)"'
1042  manual  2026-11-23T09:11:02Z
1043  manual  2026-11-23T09:11:05Z

&lt;-- [critical anomaly] Two InProgress &gt;30 min abnormal. Replication stuck usually target registry auth failure; logs in jobservice.

3.3 PromQL: Four Alerts Cover Core Risks

Harbor 2.6+ bundles exporter; metrics at core's /metrics . Four alerts cover capacity, health, scan, performance.

# 1) Quota usage >85% (3-day advance warning)
harbor_project_quota_usage_byte
  / harbor_project_quota_hard_byte > 0.85
# 2) Component liveness (any down alerts)
up{job="harbor"} == 0
# 3) Request P99 latency >2s
histogram_quantile(0.99,
  sum by (le) (rate(harbor_request_duration_seconds_bucket[5m]))
) > 2
# 4) Scan failure rate
sum(rate(harbor_scan_total{status="Error"}[15m]))
  / sum(rate(harbor_scan_total[15m])) > 0.05

Metric name trap: Harbor exporter metric prefix changed across versions ( harbor_ vs harbor_core_ ); must verify actual exposed names before upgrade.

curl -s http://172.20.12.21:8080/metrics | grep -c '^harbor_'
curl -s http://172.20.12.21:8080/metrics | grep 'quota' | head -5
harbor_project_quota_usage_byte{project="payment"}
  4.2949672960e+10
harbor_project_quota_hard_byte{project="payment"}
  1.073741824e+11

&lt;-- [judgment] Metrics carry project_name label → direct project-level alerts. If missing, quota disabled or exporter too old. Storage-side monitoring from S3/MinIO:

# MinIO bucket capacity & object count
minio_bucket_usage_total_bytes{bucket="harbor-blobs"}
minio_bucket_objects_count{bucket="harbor-blobs"}

3.4 Three Forensic Commands: GC Stuck, Scan Stuck, Push Stuck

Three "stuck" types look similar; forensic paths differ completely.

# GC stuck: check jobservice GC task logs
docker logs jobservice --tail=300 2>&1 \
  | grep -iE 'garbage|gc|delete' | tail -20
[INFO] start to run gc in job.
[INFO] start to list tags of project: payment
[INFO] found 1284 artifacts to be deleted
[WARN] failed to delete blob sha256:bb22...: 
         unexpected status code 409

&lt;-- [critical anomaly] 409 = blob still referenced. GC has time window between "mark delete" and "actually delete"; new push referencing same blob causes conflict. Re-run fixes.

# Scan stuck: check trivy adapter & jobservice queue
H=${H:-https://registry.example.com}
docker logs trivy-adapter --tail=50 2>&1 | grep -iE 'scan|error'
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/systeminfo" | jq '.scan_all_policy'
2026-11-23T10:02:11Z [ERROR] failed to scan artifact:
  context deadline exceeded (Client.Timeout exceeded)

&lt;-- [critical anomaly] deadline exceeded = trivy.yml timeout too short; large image can't finish. Default 5m → raise to 10m+.

# Push stuck: trace from nginx to registry hop-by-hop
docker exec nginx tail -5 /var/log/nginx/error.log
docker logs registry --tail=50 2>&1 | tail -20
ss -tnp state established '( sport = :5000 )' | wc -l
2026/11/23 14:31:02 [error] 27#27: *8821
  client intended to send too large body:
  3221225472 bytes, client: 172.20.11.5,
  request: "PATCH /v2/..."

&lt;-- [critical anomaly] "client intended to send too large body" = client_max_body_size active (non-zero). Set to 0 then reload. Common structure: forensics start at layer closest to user, then move inward. nginx logs show "request arrived but rejected"; registry logs show "request arrived but failed"; if both clean, problem is client.

4. Three Deep-Water Failures: Phenomenon to Rollback Closed Loop

4.1 Case 1: GC Succeeds 3×, Storage Only Drops 3% — Dangling Manifest Reference Protection

Symptom: Storage 82% → 91%, cleanup triggered. Three daily GCs all return Success , but S3 usage monotonic rise. Harbor quota shows "used 42 GB"; MinIO bucket actually 890 GB. These two numbers differ 20× → problem not in Harbor's ledger, but in what the ledger forgot. Step 1: Confirm GC params & actual deleted bytes.

curl -s -u "admin:${HARBOR_PASS}" \
  "https://registry.example.com/api/v2.0/system/gc" \
  | jq -r '.items[] | "\(.create_time) \(.job_status) \(.job_name) \(.parameters)"'
2026-11-20T02:00:11Z Success GC {"delete_untagged":false}
2026-11-21T02:00:09Z Success GC {"delete_untagged":false}
2026-11-22T02:00:13Z Success GC {"delete_untagged":false}

&lt;-- [critical anomaly] All three delete_untagged=false. When false, GC only deletes "provably orphan" blobs; dangling manifests keep protecting their layers.

docker logs jobservice --tail=400 2>&1 \
  | grep -E 'found|deleted|blobs' | tail -12
[INFO] start to scan and mark blobs
[INFO] found 412 blobs to be deleted
[INFO] deleted 41843072 bytes in total

&lt;-- [judgment] Three days each ~40 MB deleted vs 890 GB bucket = no-op. Meanwhile 412 blobs marked vs 890k total objects = completely disproportionate. Step 2: Quantify dangling manifest count.

# Count all tagless artifacts in a project
H=${H:-https://registry.example.com}
for repo in $(curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories?page_size=100" \
  | jq -r '.[].name' | sed 's|payment/||'); do
  cnt=$(curl -s -u "admin:${HARBOR_PASS}" \
    "${H}/api/v2.0/projects/payment/repositories/${repo}/
artifacts?page_size=100&with_tag=false" \
    | jq '[.[] | select((.tags // []) | length == 0)] | length')
  printf '%s %s
' "${repo}" "${cnt}"
done
api 1842
worker 1103
gateway 967

&lt;-- [critical anomaly] Three repos each thousands of tagless artifacts. These are dangling manifests, each protecting a batch of exclusive layers. Step 3: Root cause deduction. Reference chain unidirectional: tag → manifest → blob . CI builds 200×/day, each pushes new timestamped tag ; old tags deleted by retention policy. Retention deletes tags, not manifests . Manifest count = "all historical builds" minus GC-explicitly-cleaned. And delete_untagged=false ensures GC never touches them. Result: >600 GB of 890 GB are exclusive old layers protected by dangling manifests. No tag points to them, but each has its own manifest referencing it → GC judges "still referenced". One-sentence root cause: Retention manages tags, GC manages blobs, the middle manifest layer has no owner. Step 4: Fix. Order must be "delete manifests first, then GC". Reverse = wasted run.

# 1) Dry-run: count artifacts to delete & blast radius
H=${H:-https://registry.example.com}
PROJ=payment
REPO=api
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/${PROJ}/repositories/${REPO}/artifacts?page_size=100&with_tag=false" \
  | jq '[.[] | select((.tags // []) | length == 0)] | length'
1842

&lt;-- [judgment] 1842 pending delete. Before execution MUST confirm no digest-pinned release flows; else deletes in-use images.

# 2) Delete dangling artifacts (keep recent 30 days, filter by push_time)
H=${H:-https://registry.example.com}
CUTOFF=$(date -u -d '30 days ago' +%Y-%m-%dT%H:%M:%SZ)
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/${PROJ}/repositories/${REPO}/artifacts?page_size=100&with_tag=false" \
  | jq -r --arg c "${CUTOFF}" \
  '.[] | select((.tags // []) | length == 0) | select(.push_time < $c) | .digest' \
  | while read -r d; do
    curl -s -o /dev/null -w '%{http_code} %{url_effective}
' \
      -X DELETE -u "admin:${HARBOR_PASS}" \
      "${H}/api/v2.0/projects/${PROJ}/repositories/${REPO}/artifacts/${d}"
  done
200 .../payment/repositories/api/artifacts/sha256:3f9a...
200 .../payment/repositories/api/artifacts/sha256:8c1d...
200 .../payment/repositories/api/artifacts/sha256:2b3c...

&lt;-- [judgment] Each 200 = manifest deleted. Blobs not yet freed; must run GC.

# 3) Run GC again, this time with delete_untagged safety net
H=${H:-https://registry.example.com}
curl -s -X POST -u "admin:${HARBOR_PASS}" \
  -H 'Content-Type: application/json' \
  -d '{"schedule":{"type":"Manual"}, "parameters":{"delete_untagged":true}}' \
  "${H}/api/v2.0/system/gc/schedule"

Step 5: Before/after verification.

# Before
mc du myminio/harbor-blobs
892 GiB  harbor-blobs
# After
mc du myminio/harbor-blobs
curl -s -u "admin:${HARBOR_PASS}" \
  "https://registry.example.com/api/v2.0/quotas?page_size=100" \
  | jq -r '.quotas[] | select(.ref.name=="payment") | .used.resource'
268 GiB  harbor-blobs
28844871680

&lt;-- [judgment] 892 GiB → 268 GiB, 70% reclaimed. Quota stat 42G → 28.8G normal: pre-GC shared layers mis-accounted; post-GC accounting aligned. Rollback: Manifest deletion irreversible . If deleted in-use image, only recovery: re-push (local cache) or pull from replication replica. Pre-execution must: 1) confirm no image@sha256 fixed refs; 2) confirm geo-replica or local image cache exists. Root fix: Set GC delete_untagged=true permanently; change CI tag strategy from "timestamp tag" to "git SHA tag + retain last N". Former leaves dangling manifest per build; latter makes tag carry version semantics.

4.2 Case 2: docker push Hangs at 90%, Then 413

Symptom: New AI model image 3.2 GB, push stalls at 88%, finally received unexpected HTTP status: 413 Request Entity Too Large . Other 500 MB images push fine. Step 1: Confirm throttle vs hard limit.

docker push registry.example.com/ml/inference:v0.9 2>&1 | tail -8
docker exec nginx tail -20 /var/log/nginx/error.log
The push refers to repository [registry.example.com/ml/inference]
3f9a1c7e: Pushing [=================>      ]  2.81GB/3.20GB
received unexpected HTTP status: 413 Request Entity Too Large
2026/11/23 14:31:02 [error] 27#27: *8821 client intended to send
too large body: 3221225472 bytes, client: 172.20.11.5,
server: registry.example.com,
request: "PATCH /v2/ml/inference/blobs/uploads/..."

&lt;-- [critical anomaly] 3221225472 = 3 GiB exactly image size. nginx rejects at request body limit; registry never receives data. Step 2: Verify nginx effective value.

docker exec nginx nginx -T 2>/dev/null | grep -n 'client_max_body_size'
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
     client_max_body_size 1024m;

&lt;-- [critical anomaly] Effective value 1024m. Not default; someone set it for "safety". 3.2 GB &gt; 1 GB → 413. Step 3: Root cause deduction. Not Harbor bug; a config drift . Change history reconstructs:

docker exec nginx ls -l /etc/nginx/nginx.conf
docker inspect nginx --format '{{.Mounts}}' | tr ',' '
' | grep nginx
-rw-r--r-- 1 root root 4821 Nov 12 09:14 /etc/nginx/nginx.conf

[{bind  /data/harbor/common/config/nginx/nginx.conf
  /etc/nginx/nginx.conf  rw true rprivate}]

&lt;-- [judgment] Config bind-mounted; file mtime Nov 12. Someone edited that day. Root cause: Nov 12 security hardening changed client_max_body_size from 0 to 1024m , rationale "prevent huge requests blowing memory". But that assumption is wrong— proxy_request_buffering off means nginx streams, no memory pressure. Two params are a pair; changing one without the other creates this failure. Step 4: Fix.

# 1) Backup current config
cp /data/harbor/common/config/nginx/nginx.conf \
  /data/harbor/common/config/nginx/nginx.conf.bak.$(date +%Y%m%d)
# 2) Revert to 0 (unlimited), streaming safety via request_buffering
sed -i 's/client_max_body_size 1024m;/client_max_body_size 0;/' \
  /data/harbor/common/config/nginx/nginx.conf
# 3) Validate & reload (no connection drop)
docker exec nginx nginx -t
docker exec nginx nginx -s reload
nginx: /etc/nginx/nginx.conf test is successful
2026/11/23 14:38:11 [notice] 88#88: signal started

&lt;-- [judgment] Reload is graceful; in-flight connections unaffected. Don't restart—restart kills all active pushes. Step 5: Before/after comparison.

time docker push registry.example.com/ml/inference:v0.9
v0.9: digest: sha256:7d3e... size: 3148
real    1m42.318s
# Server-side throughput confirm
docker exec nginx awk '{s+=$10} END {print s/1024/1024 " MB"}' \
  /var/log/nginx/access.log
3148 MB

&lt;-- [judgment] 3.2 GB in 102 s = 31 MB/s avg. Limited by client uplink, not registry bottleneck. Rollback: Revert to 1024m works but immediately reproduces 413. Real rollback: "raise to business-acceptable value" e.g. 10240m , not back to 1024m. Root fix: Add client_max_body_size 0 to config baseline check, scripted daily audit. Pair "security hardening" changes with review because this param couples with proxy_request_buffering ; solo change guarantees breakage.

4.3 Case 3: Scan All Green, Production Finds 200+ Vulns

Symptom: Harbor scan shows 0 Critical, 0 High , image released. Two weeks later external pentest finds 200+ high-severity vulns in same image, including libssl RCE. This "scan passes but holes exist" failure is far more dangerous than scan errors because it's silent. Step 1: Confirm scan actually ran.

H=${H:-https://registry.example.com}
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories/
api/artifacts/v1.2.3?with_scan_overview=true" \
  | jq '.scan_overview'
{
  "application/vnd.security.vulnerability.report; version=1.1": {
    "report_id": "8f4e2b1a",
    "scan_status": "Success",
    "severity": "None",
    "duration": 2,
    "summary": {
      "total": 0,
      "fixable": 0
    },
    "start_time": "2026-11-22T10:14:02Z",
    "end_time": "2026-11-22T10:14:04Z"
  }
}

&lt;-- [critical anomaly] duration only 2 seconds. An 800 MB image full scan (unpack + match DB) needs ≥15 s. 2 s finish = it never parsed layers. Step 2: Check adapter logs.

docker logs trivy-adapter --tail=100 2>&1 | grep -iE 'db|error|skip' | tail -15
T10:14:02Z [INFO] Loading DB from
     /home/scanner/.cache/trivy/db/trivy.db
T10:14:02Z [WARN] DB file not found, using empty DB
T10:14:02Z [INFO] Vulnerability DB is up to date
T10:14:04Z [INFO] Scan finished, 0 vulnerabilities

&lt;-- [critical anomaly] "DB file not found, using empty DB" is key. Trivy on missing DB doesn't error; falls back to empty DB → 0 vulns. Step 3: Verify DB file actual state.

docker exec trivy-adapter ls -lh /home/scanner/.cache/trivy/db/
docker exec trivy-adapter du -sh /home/scanner/.cache/trivy/
total 0

0    /home/scanner/.cache/trivy/

&lt;-- [critical anomaly] Directory empty. DB never downloaded, never mounted. Step 4: Root cause deduction. Three clues combine: harbor.yml has skip_update: true + offline_scan: true = "don't download, use local DB".

But local DB never placed. Deployment docs said "manually download DB"; execution skipped that step.

Trivy behavior: missing DB → degrades to empty DB, returns 0 vulns, scan_status=Success .

One-sentence root cause: Offline mode + empty DB = always success, always 0 vulns. This combo emits zero errors; most dangerous failure mode. Step 5: Fix.

# 1) Download DB on internet machine (version must match adapter's trivy version)
trivy --version
trivy image --download-db-only --cache-dir /tmp/trivy-db
trivy image --download-java-db-only --cache-dir /tmp/trivy-db
Version: 0.58.1
2026-11-23T06:12:01Z [INFO] Need to update DB
T06:12:01Z [INFO] DB Repository:
     ghcr.io/aquasecurity/trivy-db
2026-11-23T06:12:28Z [INFO] DB Updated
# 2) Package & transfer
tar czf trivy-db-$(date +%Y%m%d).tgz -C /tmp/trivy-db db java-db
scp trivy-db-20261123.tgz harbor-01:/data/harbor/trivy-adapter/
# 3) Unpack to adapter mount path on Harbor node
ssh harbor-01 \
  'tar xzf /data/harbor/trivy-adapter/trivy-db-*.tgz \
    -C /data/harbor/trivy-adapter/trivy/'
ssh harbor-01 'docker restart trivy-adapter'
# 4) Verify DB loaded
docker logs trivy-adapter --tail=10 2>&1 | grep -iE 'DB|version'
docker exec trivy-adapter du -sh /home/scanner/.cache/trivy/db/
2026-11-23T06:20:11Z [INFO] DB Version: 2
2026-11-23T06:20:12Z [INFO] Vulnerability DB is up to date

68M    /home/scanner/.cache/trivy/db/

&lt;-- [judgment] 68M proves DB loaded. 0 bytes = not loaded; only reliable indicator. Step 6: Rescan & compare.

# Trigger rescan
H=${H:-https://registry.example.com}
curl -s -X POST -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories/
api/artifacts/v1.2.3/scan"
sleep 30
curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories/
api/artifacts/v1.2.3?with_scan_overview=true" \
  | jq '.scan_overview[].summary'
{
  "total": 214,
  "fixable": 178,
  "summary": {
    "Critical": 12,
    "High": 63,
    "Medium": 91,
    "Low": 48
  }
}

&lt;-- [judgment] 0 → 214 (12 Critical + 63 High). Duration 2 s → 27 s, proof of real scan. Rollback: No rollback needed, but immediately freeze that image's release and batch-rescan all images released in past two weeks. Batch rescan via Harbor API, not manual clicks:

H=${H:-https://registry.example.com}
for repo in $(curl -s -u "admin:${HARBOR_PASS}" \
  "${H}/api/v2.0/projects/payment/repositories?page_size=100" \
  | jq -r '.[].name' | sed 's|payment/||'); do
  curl -s -X POST -u "admin:${HARBOR_PASS}" \
    "${H}/api/v2.0/projects/payment/repositories/${repo}/artifacts?page_size=100" > /dev/null
  printf 'queued %s
' "${repo}"
done

Root fix: Add "DB file size > 50 MB" to patrol checks; du -sh below threshold → alert. Also flag scan_status=Success AND duration &lt; 5s as suspicious—this catches all "empty DB scans".

4.4 Common Structure Across Three Cases

Phase: Bottleneck Layer; Case 1: Manifest not reclaimed; Case 2: nginx body limit; Case 3: Vuln DB missing

Phase: Key Evidence; Case 1: GC param false; Case 2: 413 + 1 GiB limit; Case 3: Duration 2 sec

Phase: Severity; Case 1: Capacity exhaustion; Case 2: Push failure (visible); Case 3: Silent scan miss

Phase: Rollback Possible; Case 1: No; Case 2: Yes; Case 3: Yes

One pervasive rule: Every Harbor "success" needs a second question—was the object it processed correct? GC succeeds but deleted empty set; scan succeeds but DB empty; push succeeds but layer truncated by proxy (that case reports digest mismatch, actually safer). Real danger is first two: process completed, but data handled was wrong. No error logs; only "is result reasonable" detects them—GC bytes deleted, scan seconds elapsed, DB file size. These three numbers are the three probes.

5. Production Changes: Risk Matrix, One Patrol Script & Rollback Plans

5.1 Change Risk Matrix: GC & Upgrade Are Different Beasts

Harbor change actions: truly dangerous are not config tweaks, but GC & version upgrades .

Change Action: Change nginx params; Impact Scope: Global push/pull; Traffic Break?: reload = no break; Rollback Difficulty: Revert config

Change Action: Change project quota; Impact Scope: Single project; Traffic Break?: No read impact; Rollback Difficulty: Revert config

Change Action: Change retention policy; Impact Scope: Historical tags; Traffic Break?: Scheduled expiry; Rollback Difficulty: Policy revertible

Change Action: Run GC; Impact Scope: All blobs; Traffic Break?: Service up but slower; Rollback Difficulty: Irreversible

Change Action: Upgrade Harbor major; Impact Scope: Everything; Traffic Break?: Requires downtime; Rollback Difficulty: Data not downgradable

Change Action: Switch storage backend; Impact Scope: All blobs; Traffic Break?: Requires downtime; Rollback Difficulty: Image-level migration

First row's "reload no break" has precondition: NOT docker compose restart nginx . restart kills process; all in-flight push sessions drop → client gets unexpected EOF . Correct: nginx -s reload . GC's "service up but slower" expands: GC holds delete locks on many objects; pushes to same blob block. GC must run at business low-tide —hard requirement, not suggestion. Upgrade's "data not downgradable" most underestimated: every major upgrade runs migratedb ; schema_version once upgraded, old version refuses to start on incompatible schema. Must rehearse upgrade on snapshot before touching prod.

5.2 Patrol Script: Turn Three Probes into Scheduled Checks

Script does one thing: use three numbers to judge if Harbor is "fake healthy". It fixes nothing, only outputs judgment.

#!/usr/bin/env bash
# /usr/local/bin/harbor-healthcheck.sh
# Purpose: fake-health patrol (GC really deletes / scan really scans / DB really there)
set -euo pipefail
IFS=$'
\t'

HARBOR=${HARBOR:-"https://registry.example.com"}
USER=${HARBOR_USER:-"admin"}
PASS=${HARBOR_PASS:?must set HARBOR_PASS}
MIN_DB_MB=${MIN_DB_MB:-50}
MIN_SCAN_SEC=${MIN_SCAN_SEC:-5}
TRIVY_CT=${TRIVY_CT:-trivy-adapter}
BLOB_DIR=${BLOB_DIR:-/data/harbor/registry}

warn=0
fail=0

say_ok()  { printf '[ OK ] %s
' "$1"; }
say_warn() { warn=$((warn+1)); printf '[WARN] %s
' "$1"; }
say_fail() { fail=$((fail+1)); printf '[FAIL] %s
' "$1"; }

api() {
  curl -sS -m 10 -u "${USER}:${PASS}" "${HARBOR}/api/v2.0$1"
}

echo "== 1. Trivy vuln DB really loaded =="
if docker inspect "${TRIVY_CT}" >/dev/null 2>&1; then
  db_mb=$(docker exec "${TRIVY_CT}" sh -c \
    'du -sm /home/scanner/.cache/trivy/db 2>/dev/null | cut -f1' || echo 0)
  db_mb=${db_mb:-0}
  if [[ "${db_mb}" -ge "${MIN_DB_MB}" ]]; then
    say_ok "trivy db ${db_mb}MB (>= ${MIN_DB_MB})"
  else
    say_fail "trivy db only ${db_mb}MB, scanning returns 0 vulns"
  fi
  db_mtime=$(docker exec "${TRIVY_CT}" sh -c \
    'stat -c %y /home/scanner/.cache/trivy/db/trivy.db 2>/dev/null | cut -d" " -f1' || echo unknown)
  echo "[INFO] db mtime: ${db_mtime}"
else
  say_warn "container ${TRIVY_CT} not found"
fi

echo "== 2. Last GC really freed space =="
gc_json=$(api "/system/gc" || echo '{}')
last=$(printf '%s' "${gc_json}" | jq -r '.items[-1].parameters // "{}"' || echo '{}')
untagged=$(printf '%s' "${last}" | jq -r '.delete_untagged // false' || echo false)
status=$(printf '%s' "${gc_json}" | jq -r '.items[-1].job_status // "none"' || echo none)
printf '[INFO] gc status=%s untagged=%s
' "${status}" "${untagged}"
if [[ "${untagged}" == "true" ]]; then
  say_ok "gc collects untagged manifests"
else
  say_warn "gc delete_untagged=false, storage will not shrink"
fi

echo "== 3. Scan duration reasonable (catch empty DB scans) =="
repo_list=$(api "/projects?page_size=20" | jq -r '.[].name' || true)
fast=0
checked=0
for p in ${repo_list}; do
  art=$(api "/projects/${p}/repositories?page_size=5" | jq -r '.[0].name // empty' 2>/dev/null | sed "s|${p}/||")
  [[ -z "${art}" ]] && continue
  dur=$(api "/projects/${p}/repositories/${art}/artifacts?page_size=5&with_scan_overview=true" | jq -r '.[0].scan_overview[]?.duration // empty' | head -1)
  [[ -z "${dur}" ]] && continue
  checked=$((checked+1))
  d=${dur%s}
  if [[ "${d}" -lt "${MIN_SCAN_SEC}" ]]; then
    fast=$((fast+1))
    printf '[SUSP] %s/%s duration %ss
' "${p}" "${art}" "${d}"
  fi
done
if [[ "${checked}" -eq 0 ]]; then
  say_warn "no scanned artifact found"
elif [[ "${fast}" -gt 0 ]]; then
  say_fail "${fast}/${checked} scans < ${MIN_SCAN_SEC}s"
else
  say_ok "${checked} scans all took >= ${MIN_SCAN_SEC}s"
fi

echo "== 4. Quota watermarks =="
api "/quotas?page_size=100" | jq -r '.quotas[] | select(.hard.resource > 0) | select((.used.resource / .hard.resource) > 0.85) | "\(.ref.name) \(((.used.resource / .hard.resource) * 100) | floor)%"' | while read -r line; do
  [[ -n "${line}" ]] && say_warn "quota high: ${line}"
done

echo "== 5. Dangling artifact count =="
total=0
for p in ${repo_list}; do
  n=$(api "/projects/${p}/artifacts?page_size=100&with_tag=false" | jq '[.[]? | select((.tags // []) | length == 0)] | length' || echo 0)
  total=$((total+n))
done
if [[ "${total}" -gt 500 ]]; then
  say_warn "untagged artifacts: ${total}, see GC"
else
  say_ok "untagged artifacts: ${total}"
fi

echo "== 6. Local blob dir vs API scope =="
if [[ -d "${BLOB_DIR}" ]]; then
  disk=$(du -sm "${BLOB_DIR}" 2>/dev/null | cut -f1 || echo 0)
  echo "[INFO] on-disk: ${disk}MB"
fi

printf '
== summary: warn=%s fail=%s ==
' "${warn}" "${fail}"
[[ "${fail}" -eq 0 ]] || exit 1

Typical output & judgment:

sudo HARBOR_PASS="$(cat /etc/harbor/healthcheck.env)" \
  /usr/local/bin/harbor-healthcheck.sh
== 1. Trivy 漏洞库是否真的加载 ==
[ OK ] trivy db 68MB (>= 50)
[INFO] db mtime: 2026-11-23
== 2. 最近一次 GC 是否真的释放了空间 ==
[INFO] last gc status=Success delete_untagged=false
[WARN] gc delete_untagged=false, storage will not shrink
== 3. 扫描耗时是否合理(抓空库扫描) ==
[SUSP] payment/api scan duration 2s
[FAIL] 1/8 scans finished under 5s
== 5. 悬空 artifact 数量 ==
[WARN] untagged artifacts: 1842 (consider delete_untagged)

== summary: warn=3 fail=1 ==

&lt;-- [critical anomaly] Two alerts point to same root cause: GC doesn't delete dangling manifests, scan finishes in 2 s. These are exactly the probes from Case 1 &amp; Case 3. Script's MIN_SCAN_SEC=5 threshold basis: minimal alpine image (~8 MB) full scan ~3-4 s (unpack + read DB); <5 s basically confirms no layer parsing. du -sm reading DB size is more reliable than any log; logs can print "up to date" but file size doesn't lie.

5.3 Rollback Plans: Three Change Classes' Exit Paths

① Config change rollback (safest)

# Backup → change → validate → reload; rollback = copy .bak back
cd /data/harbor
cp common/config/nginx/nginx.conf /tmp/nginx.conf.rollback
./prepare
docker compose up -d

./prepare re-renders all configs; it's Harbor's config master gate . Skip it and edit container files directly → next up -d overwrites back—#1 cause of "change didn't stick". ② GC & retention policy mistakes Manifest deletion irreversible. Damage control only two paths:

# Path A: Pull from replication replica (if geo Harbor exists)
skopeo copy \
  docker://backup-registry.example.com/payment/api:v1.2.3 \
  docker://registry.example.com/payment/api:v1.2.3
# Path B: Re-push from CI build cache
docker pull ci-cache.local/payment/api:sha-3f9a1c7e
docker tag ci-cache.local/payment/api:sha-3f9a1c7e \
  registry.example.com/payment/api:v1.2.3
docker push registry.example.com/payment/api:v1.2.3

Both require post-facto source exists . So GC precondition: at least one usable replica, or CI retains build artifacts. Without both, GC is irreversible high-risk op. ③ Version upgrade rollback

# Pre-upgrade: DB snapshot (only reliable exit)
docker exec postgres pg_dump -U harbor registry \
  | gzip > /backup/harbor-registry-$(date +%Y%m%d).sql.gz
ls -lh /backup/harbor-registry-*.sql.gz
412M  Nov 23 08:12  /backup/harbor-registry-20261123.sql.gz

&lt;-- [judgment] 400 MB registry DB normal (hundreds of thousands artifacts). If only few MB, tables empty or wrong DB. Upgrade failure rollback sequence:

# 1) Stop services
cd /data/harbor && docker compose down
# 2) Restore previous version compose & config (Harbor installer keeps old dir)
mv /data/harbor /data/harbor.failed
mv /data/harbor.prev /data/harbor
# 3) Restore database
gunzip -c /backup/harbor-registry-20261123.sql.gz \
  | docker exec -i postgres psql -U harbor -d registry
# 4) Start services & verify schema version
cd /data/harbor && docker compose up -d

Order cannot reverse : must restore code first, then data. Reverse → new version's migrator upgrades old DB again, stuck in middle state with no way back.

5.4 Six Engineering Iron Laws

Delete tag ≠ free space; GC only deletes blobs with zero manifest refs. Middle manifest layer cleans itself; delete_untagged=true only worry-free option.

Quota accounting pro-rates shared layers per project. Deleting project with most shared-layer refs makes remaining project's usage jump—implementation detail, not bug.

client_max_body_size & proxy_request_buffering are a pair. Former limits body size; latter decides if disk spill needed. Change one alone → guaranteed breakage.

Offline Trivy empty DB = silent failure. Returns 0 vulns, scan_status=Success, duration 2 s. All three together = empty DB.

GC & upgrades must run at low-tide; upgrade pre-req = DB snapshot. Harbor schema one-way; no snapshot = no exit.

./prepare is config master gate. All harbor.yml changes must pass through it for re-render; direct container file edits get overwritten on next start.

Final non-param rule: Registry monitoring focus isn't QPS, but "are three numbers reasonable" —GC bytes freed, scan seconds elapsed, vuln DB file size. Any one abnormal = registry in fake-health state, yet zero alerts fire.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Published

AI-assisted summary

Report an issue with this article
Garbage CollectionTroubleshootingHarborVulnerability ScanningContainer RegistryOCITrivyProduction Operations

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion