【问题标题】:How to pull images from private docker registry only?如何仅从私有 docker registry 中拉取镜像?
【发布时间】:2023-02-10 18:22:21
【问题描述】:
有没有办法只从私有注册表中提取图像并阻止从公共注册表 docker hub 中提取图像?
我使用的是 Nexus 注册表,我可以从中配置和提取图像。我正在尝试实现一种只从我的私有注册表推送图像的方法,这样我就可以跟踪我正在使用的 docker 图像,然后在其中应用一些安全分析。但我仍然可以从我的计算机中的 docker hub 中提取图像。有没有办法阻止它?
【问题讨论】:
标签:
docker
nexus
docker-registry
【解决方案1】:
有不同的方法,你可以怎么做。
我在这里假设您使用的是 Kubernetes:
- 在集群上使用准入控制器将 Pod 规范重写到您的内部注册表
- 容器运行时现在有限制注册表的选项,cri-o 和 containerd 有这个选项。
如果您使用的是 CNCF Harbor [1]、[2] 之类的东西,您可以为第 3 方注册中心创建代理,然后使用 Kyverno 重写 Pod 规范。
用 Kyverno 替换 Image Registry
与其阻止来自外部注册中心的 Pod,还可以改变它们,因此拉取被定向到批准的注册中心。在某些情况下,这些注册表可以充当拉通代理,并且可以在未缓存的情况下获取图像。此策略将“image:tag”或“example.container-registry.com/image:tag”形式的所有图像突变为myregistry.corp.com/。图像名称中的任何路径都将被保留。请注意,这会直接改变 Pod 而不是它们的控制器。如果需要,可以更改它,但如果是这样,可能不需要在 Pod 上匹配。
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: replace-image-registries
spec:
background: false
rules:
# We only allow a known set of approved registries to be used in our clusters
- name: validate-registries
match:
resources:
kinds:
- Pod
validate:
message: "Unapproved image registry."
pattern:
spec:
containers:
- image: "example.container-registry.com/* | quay.io/* | gcr.io/* | ghcr.io/* | docker.io/*"
# Rewrite all the references for our approved external registries
- name: replace-registries
match:
resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
spec:
containers:
- (name): "*"
image: |-
{{ regex_replace_all('(quay.io|gcr.io|ghcr.io|docker.io)/(.*)', '{{@}}', 'example.container-registry.com/$1/$2') }}
# At this point we expect everything that has a registry prefix to have been transformed
# example.container-registry.com.*. We are left with references like:
#
# - velero/velero:v1.6.2
# - nginx:latest
# - nginx
#
# Without interfering with our newly rewritten references that start with example.container-registry.com
- name: replace-docker
match:
resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
spec:
containers:
- (name): "*"
image: |-
{{ regex_replace_all('^([^example.container-registry.com].*)', '{{@}}', 'example.container-registry.com/docker.io/$1') }}
这里的回购有一些例子:https://github.com/jvanzyl/kyverno-registries