Docker Registry构建Docker私库

Docker Registry

1. 自签证书

mkdir -p certs
# generate self-signed certifacate
openssl req \
  -newkey rsa:4096 -nodes -sha256 -keyout certs/domain.key \
  -x509 -days 365 -out certs/domain.crt

生成自签证书时,有个地方需要注意,域名可以自己随便定义一个,然后每个使用域名连接这个机器的主机必须更改hosts文件.

-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:gitlab.cicd.com
Email Address []:

2. 运行registry镜像

docker run -d \
  --restart=always \
  --name registry \
  -v "$(pwd)"/certs:/certs \
  -e REGISTRY_HTTP_ADDR=0.0.0.0:443 \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \
  -p 443:443 \
  registry:2

3. 使得Linux信任自签证书

mkdir -p /etc/docker/certs.d/gitlab.cicd.com:5000
cp certs/domain.crt /etc/docker/certs.d/gitlab.cicd.com:5000/ca.crt
# redhat系列操作系统,比如centos
cp domain.crt /etc/pki/ca-trust/source/anchors/gitlab.cicd.com.crt 
update-ca-trust

这里参考:Docker still complains about the certificate when using authentication?

这一步如果不做会出现:

[root@localhost ~]# docker push gitlab.cicd.com/nginx
The push refers to repository [gitlab.cicd.com/nginx]
Get https://gitlab.cicd.com/v2/: x509: certificate signed by unknown authority

4. 修改/etc/docker/daemon.json

{
  "insecure-registries" : ["gitlab.cicd.com:5000"]
}

重启Docker服务,比如systemctl retstart docker

5. 登录Docker & 推送镜像

# 这里随便输入用户名和密码
docker login
# 成功之后,随便推送个镜像试一试。这个镜像路径吗,需要加上docker私库的所在的机器域名。官方的镜像才不用加,其他的都要加。
docker tag busybox gitlab.cicd.com/busybox
# push私库
[root@localhost ~]# docker push gitlab.cicd.com/busybox
The push refers to repository [gitlab.cicd.com/busybox]
1079c30efc82: Pushed 
latest: digest: sha256:a7766145a775d39e53a713c75b6fd6d318740e70327aaa3ed5d09e0ef33fc3df size: 527

其他机器要拉取镜像,第3-5是需要做的。

kubernetes拉取私库镜像

创建一个secret就可以了

kubectl create secret generic regcred \
--from-file=.dockerconfigjson=/root/.docker/config.json --type=kubernetes.io/dockerconfigjson

然后使用这个Secret来拉取镜像:

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  namespace: default
spec:
  containers:
  - name: busybox
    image: gitlab.cicd.com/alpine
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
  imagePullSecrets:
    - name: regcred   # 使用Secret
  restartPolicy: Always

参考:Pull an Image from a Private Registry

你可能感兴趣的:(虚拟化与自动化运维)