1. Harbor 概述与核心特性
🏢 企业级特性
- 基于角色的访问控制(RBAC)
- 多租户支持与项目隔离
- LDAP/AD 身份验证集成
- 审计日志与合规性报告
- 镜像漏洞扫描(Clair/Trivy)
🔄 镜像管理
- 镜像复制与同步
- 镜像签名与内容信任
- 镜像生命周期策略
- Helm Chart 托管
- OCI Artifact 支持
🛡️ 安全能力
- CVE 漏洞扫描
- 镜像签名验证
- 敏感信息检测
- 访问策略控制
- 安全基线检查
📈 可扩展性
- 水平扩展架构
- 高可用部署模式
- 对象存储后端
- 外部数据库支持
- RESTful API
1.1 Harbor 架构组成
┌─────────────────────────────────────────────────────────────────┐
│ Harbor Architecture │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Portal │ │ Core │ │ JobSvc │ │
│ │ (UI Web) │ │ (API) │ │ (Scheduler) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ┌────────────┴────────────┐ │
│ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ │
│ │ Registry │ │ Clair │ │
│ │ (Storage) │ │ (Scanner) │ │
│ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ │
│ │ PostgreSQL │ │ Redis │ │
│ │ (Database) │ │ (Cache) │ │
│ └─────────────┘ └─────────────┘ │
│ │
│ External Services (Optional): │
│ • LDAP/AD Authentication │
│ • Object Storage (S3/GCS/OSS) │
│ • External PostgreSQL/Redis │
│ │
└─────────────────────────────────────────────────────────────────┘
2. 系统要求与环境准备
2.1 硬件配置要求
| 资源 |
最低配置 |
推荐配置 |
生产环境 |
| CPU |
2 Core |
4 Core |
8+ Core |
| 内存 |
4 GB |
8 GB |
16+ GB |
| 磁盘 |
40 GB |
160 GB |
500GB+ SSD |
| 网络 |
1 Gbps |
1 Gbps |
10 Gbps |
2.2 软件依赖
Docker Compose 部署
- Docker Engine 20.10.0+
- Docker Compose 2.0.0+
- Linux: Ubuntu 18.04+, CentOS 7+
- OpenSSL latest(证书生成)
Kubernetes 部署
- Kubernetes 1.20+
- Helm 3.2.0+
- Ingress Controller(Nginx/Traefik)
- StorageClass(动态存储)
外部服务(可选)
- PostgreSQL 12+(外部数据库)
- Redis 5.0+(外部缓存)
- 对象存储(S3/OSS/GCS)
- LDAP/AD 服务器
2.3 端口要求
| 端口 |
协议 |
用途 |
可修改 |
| 443 |
HTTPS |
Harbor Portal 和 API |
是 |
| 80 |
HTTP |
HTTP 重定向到 HTTPS |
是 |
| 5000 |
HTTPS |
Registry API(推送/拉取) |
是 |
| 5432 |
TCP |
PostgreSQL 数据库 |
内部使用 |
| 6379 |
TCP |
Redis 缓存 |
内部使用 |
2.4 环境诊断命令
lscpu | grep "CPU(s)"
free -h
df -h /
df -h /var/lib/docker
docker --version
docker compose version
netstat -tlnp | grep -E ':(80|443|5000)'
ss -tlnp | grep -E ':(80|443|5000)'
curl -I https://github.com
curl -I https://hub.docker.com
kubectl version --short
kubectl get nodes
helm version
kubectl get sc
kubectl get ingress -A
3. 安装方式选择与对比
| 安装方式 |
适用场景 |
优点 |
缺点 |
推荐度 |
| Docker Compose |
开发测试/中小规模 |
简单快速、资源占用少 |
单点故障、扩展性差 |
⭐⭐⭐⭐ |
| Helm on K8s |
生产环境/大规模 |
高可用、易扩展、自动化 |
复杂度高、需要 K8s |
⭐⭐⭐⭐⭐ |
| 离线安装包 |
内网隔离环境 |
无需外网、一次性下载 |
包体积大、更新麻烦 |
⭐⭐⭐⭐ |
| 源码编译 |
定制开发 |
完全掌控、可定制 |
复杂耗时、维护成本高 |
⭐⭐ |
💡 推荐方案:
- 开发/测试环境:Docker Compose 部署(快速简单)
- 生产环境:Kubernetes Helm 部署(高可用、易扩展)
- 内网环境:离线安装包 + Docker Compose
4. Docker Compose 部署(单机版)
步骤 1:下载安装 Harbor 离线安装包
mkdir -p /opt/harbor && cd /opt/harbor
wget https://github.com/goharbor/harbor/releases/download/v2.11.0/harbor-offline-installer-v2.11.0.tgz
wget https://github.com/goharbor/harbor/releases/download/v2.11.0/harbor-offline-installer-v2.11.0.tgz.asc
gpg --keyserver hkps://keyserver.ubuntu.com --receive-keys 644FF454C0B4115C
gpg --verify harbor-offline-installer-v2.11.0.tgz.asc
tar -xzf harbor-offline-installer-v2.11.0.tgz
cd harbor
ls -la
步骤 2:配置 harbor.yml
cp harbor.yml.tmpl harbor.yml
vi harbor.yml
hostname: harbor.yourcompany.com
http:
port: 8080
https:
port: 443
certificate: /data/cert/server.crt
private_key: /data/cert/server.key
harbor_admin_password: Harbor12345
database:
password: root123
max_idle_conns: 50
max_open_conns: 1000
data_volume: /data/harbor
clair:
updaters_interval: 12
jobservice:
max_job_workers: 10
notification:
webhook_job_max_retry: 10
log:
level: info
local:
rotate_count: 50
rotate_size: 200M
location: /var/log/harbor
_version: 2.11.0
storage_service:
filesystem:
maxthreads: 100
s3:
region: us-east-1
bucket: harbor-storage
accesskey: AKIAIOSFODNN7EXAMPLE
secretkey: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
步骤 3:生成自签名证书(测试环境)
mkdir -p /data/cert
openssl genrsa -out /data/cert/ca.key 4096
openssl req -new -x509 -days 3650 \
-key /data/cert/ca.key \
-subj "/C=CN/ST=Beijing/L=Beijing/O=YourCompany/OU=IT/CN=harbor.yourcompany.com" \
-out /data/cert/ca.crt
openssl genrsa -out /data/cert/server.key 4096
openssl req -new -key /data/cert/server.key \
-subj "/C=CN/ST=Beijing/L=Beijing/O=YourCompany/OU=IT/CN=harbor.yourcompany.com" \
-out /data/cert/server.csr
openssl x509 -req -days 3650 \
-in /data/cert/server.csr \
-CA /data/cert/ca.crt \
-CAkey /data/cert/ca.key \
-CAcreateserial \
-out /data/cert/server.crt
chmod 600 /data/cert/server.key
chmod 644 /data/cert/server.crt /data/cert/ca.crt
cp /data/cert/ca.crt /usr/local/share/ca-certificates/harbor-ca.crt
update-ca-certificates
mkdir -p /etc/docker/certs.d/harbor.yourcompany.com
cp /data/cert/ca.crt /etc/docker/certs.d/harbor.yourcompany.com/
步骤 4:执行安装脚本
./install.sh
./install.sh --with-trivy --with-chartmuseum
docker compose ps
docker compose logs -f
步骤 5:验证安装
docker compose ps
curl -k https://harbor.yourcompany.com
curl -k -u admin:Harbor12345 https://harbor.yourcompany.com/api/v2.0/systeminfo
docker login harbor.yourcompany.com -u admin -p Harbor12345
docker pull hello-world
docker tag hello-world harbor.yourcompany.com/library/hello-world:latest
docker push harbor.yourcompany.com/library/hello-world:latest
docker rmi harbor.yourcompany.com/library/hello-world:latest
docker pull harbor.yourcompany.com/library/hello-world:latest
5. Kubernetes Helm 部署(高可用)
5.1 前置要求
📋 Helm 部署前置条件:
- Kubernetes 集群 1.20+
- Helm 3.2.0+
- 高可用 Ingress Controller
- 外部 PostgreSQL 数据库(可选但推荐)
- 外部 Redis 集群(可选但推荐)
- 共享存储或对象存储
5.2 添加 Helm Repository
helm repo add harbor https://helm.goharbor.io
helm repo update
helm search repo harbor --versions
helm fetch harbor/harbor --version 1.14.0 --untar
cd harbor
5.3 配置 values.yaml
expose:
type: ingress
tls:
enabled: true
certSource: secret
secret:
secretName: harbor-tls-secret
ingress:
hosts:
core: harbor.yourcompany.com
annotations:
nginx.ingress.kubernetes.io/proxy-body-size: "0"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
externalURL: https://harbor.yourcompany.com
portal:
replicas: 2
core:
replicas: 2
resources:
requests:
memory: 256Mi
cpu: 100m
limits:
memory: 2Gi
cpu: 2000m
jobservice:
replicas: 2
maxJobWorkers: 10
registry:
replicas: 2
resources:
requests:
memory: 256Mi
cpu: 100m
database:
type: external
external:
host: postgresql-ha.postgres.svc.cluster.local
port: 5432
username: harbor
password: your_password
coreDatabase: harbor_core
clairDatabase: harbor_clair
notaryServerDatabase: harbor_notary_server
notarySignerDatabase: harbor_notary_signer
redis:
type: external
external:
host: redis-master.redis.svc.cluster.local
port: 6379
password: your_redis_password
persistence:
enabled: true
persistentVolumeClaim:
registry:
storageClass: nfs-client
accessMode: ReadWriteMany
size: 100Gi
chartmuseum:
storageClass: nfs-client
accessMode: ReadWriteMany
size: 20Gi
trivy:
enabled: true
replicas: 2
notary:
enabled: true
chartmuseum:
enabled: true
5.4 创建 TLS Secret
kubectl create namespace harbor
kubectl create secret tls harbor-tls-secret \
--cert=/path/to/tls.crt \
--key=/path/to/tls.key \
-n harbor
kubectl get secret harbor-tls-secret -n harbor
5.5 安装 Harbor
helm install harbor harbor/harbor \
--namespace harbor \
--values values.yaml \
--version 1.14.0
helm install harbor . \
--namespace harbor \
--values values.yaml
helm status harbor -n harbor
helm list -n harbor
kubectl get pods -n harbor -w
kubectl get svc -n harbor
kubectl get ingress -n harbor
5.6 升级与卸载
helm upgrade harbor harbor/harbor \
--namespace harbor \
--values values.yaml \
--version 1.15.0
helm rollback harbor -n harbor
helm history harbor -n harbor
helm uninstall harbor -n harbor
kubectl delete pvc -n harbor -l app=harbor
6. HTTPS 证书配置
6.1 Let's Encrypt 免费证书
apt-get install certbot python3-certbot-nginx -y
certbot certonly --standalone \
-d harbor.yourcompany.com \
--email admin@yourcompany.com \
--agree-tos \
--non-interactive
crontab -e
6.2 Nginx Ingress 自动申请证书
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.0/cert-manager.yaml
cat > cluster-issuer.yaml << EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@yourcompany.com
privateKeySecretRef:
name: letsencrypt-prod-key
solvers:
- http01:
ingress:
class: nginx
EOF
kubectl apply -f cluster-issuer.yaml
expose:
tls:
certSource: secret
auto:
commonName: harbor.yourcompany.com
issuerName: letsencrypt-prod
issuerKind: ClusterIssuer
7. 用户与项目管理
7.1 创建项目
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/projects \
-d '{
"project_name": "my-project",
"public": false,
"metadata": {
"enable_content_trust": true,
"prevent_vulnerable_images": true
}
}'
curl -k -u admin:Harbor12345 \
https://harbor.yourcompany.com/api/v2.0/projects
7.2 创建用户
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/users \
-d '{
"username": "developer1",
"email": "developer1@yourcompany.com",
"realname": "Developer One",
"password": "SecurePass123!",
"comment": "Development team member"
}'
curl -k -u admin:Harbor12345 \
"https://harbor.yourcompany.com/api/v2.0/users?page=1&page_size=10"
curl -k -X DELETE \
-u admin:Harbor12345 \
https://harbor.yourcompany.com/api/v2.0/users/123
7.3 添加项目成员
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/projects/1/members \
-d '{
"role_id": 2,
"member_user": {
"username": "developer1"
}
}'
8. RBAC 权限模型详解
8.1 Harbor 角色体系
| 角色 |
系统权限 |
项目权限 |
适用场景 |
| 系统管理员 |
全部权限 |
所有项目 |
Harbor 运维团队 |
| 项目管理员 |
无 |
项目管理、成员管理 |
项目负责人 |
| 开发者 |
无 |
推送/拉取/删除镜像 |
开发工程师 |
| 维护者 |
无 |
推送/拉取(不可删除) |
CI/CD 系统 |
| 访客 |
无 |
仅拉取镜像 |
只读用户 |
| 有限访客 |
无 |
仅拉取镜像(部分 API 受限) |
外部合作方 |
8.2 自定义角色(Harbor 2.10+)
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/usergroups \
-d '{
"group_name": "devops-team",
"group_type": 1,
"ldap_group_dn": "cn=devops,ou=groups,dc=example,dc=com"
}'
curl -k -X PUT \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/projects/1/members/456 \
-d '{
"role_id": 4
}'
8.3 LDAP/AD 集成
curl -k -X PUT \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/configurations \
-d '{
"auth_mode": "ldap_auth",
"ldap_url": "ldap://ldap.yourcompany.com",
"ldap_base_dn": "dc=example,dc=com",
"ldap_search_dn": "cn=admin,dc=example,dc=com",
"ldap_search_password": "ldap_password",
"ldap_filter": "(objectClass=person)",
"ldap_uid_attribute": "uid",
"ldap_scope": 2,
"ldap_connection_timeout": 10,
"ldap_verify_cert": true
}'
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/usergroups \
-d '{
"group_type": 1,
"ldap_group_dn": "cn=developers,ou=groups,dc=example,dc=com"
}'
9. 机器人账户配置
9.1 什么是机器人账户
机器人账户是专为 CI/CD 系统和自动化脚本设计的轻量级账户,具有以下特点:
- 细粒度权限控制(可精确到具体操作)
- 可设置过期时间
- 可限制访问特定项目
- 不支持 Web 登录,仅用于 API/Docker CLI
9.2 创建机器人账户
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/projects/1/robots \
-d '{
"name": "jenkins-deploy",
"description": "Jenkins CI deployment robot",
"expires_at": 1735689600,
"permissions": [
{
"kind": "project",
"namespace": "my-project",
"access": [
{"resource": "repository", "action": "push"},
{"resource": "repository", "action": "pull"},
{"resource": "artifact", "action": "read"},
{"resource": "artifact", "action": "create"},
{"resource": "tag", "action": "create"},
{"resource": "tag", "action": "delete"}
]
}
]
}'
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/robots \
-d '{
"name": "global-ci",
"level": "system",
"permissions": [
{
"kind": "project",
"namespace": "project-a",
"access": [{"resource": "repository", "action": "push"}]
},
{
"kind": "project",
"namespace": "project-b",
"access": [{"resource": "repository", "action": "pull"}]
}
]
}'
9.3 使用机器人账户
docker login harbor.yourcompany.com \
-u 'robot$jenkins-deploy' \
-p 'JaNgT0kEn123456789...'
pipeline {
agent any
environment {
HARBOR_REGISTRY = 'harbor.yourcompany.com'
HARBOR_USER = 'robot$jenkins-deploy'
HARBOR_PASSWORD = credentials('harbor-robot-token')
}
stages {
stage('Build & Push') {
steps {
script {
docker.withRegistry("https://${HARBOR_REGISTRY}",
[usernamePassword(credentialsId: 'harbor-robot-token',
usernameVariable: 'USER',
passwordVariable: 'PASS')]) {
def image = docker.build("${HARBOR_REGISTRY}/my-project/app:${BUILD_NUMBER}")
image.push()
}
}
}
}
}
}
10. CI/CD 集成配置
10.1 Jenkins 集成
pipeline {
agent any
tools {
maven 'Maven 3.8'
}
environment {
HARBOR_URL = 'https://harbor.yourcompany.com'
PROJECT_NAME = 'backend-service'
}
stages {
stage('Checkout') {
steps { git url: 'git@gitlab:team/backend.git' }
}
stage('Build') {
steps { sh 'mvn clean package -DskipTests' }
}
stage('Unit Test') {
steps { sh 'mvn test' }
}
stage('Build Image') {
steps {
script {
def image = docker.build("${HARBOR_URL}/${PROJECT_NAME}:${env.BUILD_NUMBER}")
}
}
}
stage('Push to Harbor') {
steps {
script {
docker.withRegistry(HARBOR_URL, 'harbor-credentials') {
def image = docker.image("${HARBOR_URL}/${PROJECT_NAME}:${env.BUILD_NUMBER}")
image.push()
image.push('latest')
}
}
}
}
stage('Vulnerability Scan') {
steps {
sh '''
curl -k -X POST \
-u ${HARBOR_USER}:${HARBOR_PASSWORD} \
"${HARBOR_URL}/api/v2.0/projects/${PROJECT_NAME}/repositories/${PROJECT_NAME}/artifacts/latest/scan"
'''
}
}
}
}
10.2 GitLab CI 集成
variables:
HARBOR_URL: harbor.yourcompany.com
PROJECT: my-project
APP_NAME: frontend-app
stages:
- build
- test
- package
- deploy
build:
stage: build
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
docker-build:
stage: package
image: docker:24
services:
- docker:24-dind
before_script:
- docker login -u ${HARBOR_ROBOT_USER} -p ${HARBOR_ROBOT_PASSWORD} ${HARBOR_URL}
script:
- docker build -t ${HARBOR_URL}/${PROJECT}/${APP_NAME}:${CI_COMMIT_SHA} .
- docker push ${HARBOR_URL}/${PROJECT}/${APP_NAME}:${CI_COMMIT_SHA}
- docker tag ${HARBOR_URL}/${PROJECT}/${APP_NAME}:${CI_COMMIT_SHA} ${HARBOR_URL}/${PROJECT}/${APP_NAME}:latest
- docker push ${HARBOR_URL}/${PROJECT}/${APP_NAME}:latest
only:
- main
- develop
deploy:
stage: deploy
script:
- kubectl set image deployment/${APP_NAME} ${APP_NAME}=${HARBOR_URL}/${PROJECT}/${APP_NAME}:${CI_COMMIT_SHA}
environment:
name: production
url: https://app.yourcompany.com
when: manual
only:
- main
11. 镜像复制与同步
11.1 配置复制规则
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/registries \
-d '{
"name": "backup-harbor",
"type": "harbor",
"url": "https://backup-harbor.example.com",
"credential": {
"type": "basic",
"access_key": "admin",
"access_secret": "BackupHarbor123"
}
}'
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/replication/policies \
-d '{
"name": "backup-to-dr",
"description": "Replicate all images to disaster recovery site",
"src_registry": null,
"dest_registry": 1,
"trigger": {
"type": "scheduled",
"trigger_settings": {
"cron": "0 0 * * *"
}
},
"filters": [
{
"type": "project",
"value": "production/**"
},
{
"type": "tag",
"value": "v*.*.*,latest"
}
],
"deletion": true,
"override": true,
"copy_by_chunk": false
}'
curl -k -X POST \
-u admin:Harbor12345 \
-H "Content-Type: application/json" \
https://harbor.yourcompany.com/api/v2.0/replication/executions \
-d '{"policy_id": 1}'
11.2 复制策略类型
| 策略类型 |
说明 |
适用场景 |
| Push-based |
主动推送到目标仓库 |
备份、多地域分发 |
| Pull-based |
从源仓库拉取 |
集中管理、镜像聚合 |
| 实时复制 |
镜像推送时立即复制 |
高可用、灾备 |
| 定时复制 |
按 Cron 表达式定时执行 |
定期同步、带宽优化 |
12. 监控告警与运维
12.1 Prometheus 监控指标
curl -k https://harbor.yourcompany.com/metrics
scrape_configs:
- job_name: 'harbor'
static_configs:
- targets: ['harbor.yourcompany.com']
scheme: https
metrics_path: /metrics
basic_auth:
username: admin
password: Harbor12345
12.2 Grafana 仪表盘
📊 推荐监控面板:
- 系统健康状态(CPU、内存、磁盘)
- 镜像仓库统计(项目数、仓库数、制品数)
- 存储使用情况(配额、使用率)
- 漏洞扫描统计(扫描次数、漏洞数量)
- 复制任务状态(成功率、延迟)
- API 请求指标(QPS、错误率、延迟)
12.3 日常运维命令
cd /opt/harbor/harbor
docker compose restart
docker compose stop
docker compose start
docker compose logs -f core
docker compose logs -f registry
tail -f /var/log/harbor/core.log
docker compose exec core bash
docker compose exec registry bash
docker compose exec postgresql pg_dumpall \
-U postgres > /backup/harbor_db_$(date +%Y%m%d).sql
cat /backup/harbor_db_20260312.sql | \
docker compose exec -T postgresql psql -U postgres
docker image prune -af --filter "until=168h"
12.4 备份策略
crontab -e
0 2 * * * /opt/harbor/backup-harbor.sh >> /var/log/harbor-backup.log 2>&1