生成自签名证书

因为没有公网ip和域名,所以这里修改/etc/pki/tls/openssl.cnf以生成带SAN 扩展的证书。 在openssl.cnf文件中修改以下内容:

1
2
3
[ v3_ca ]
#指定ip
subjectAltName=IP:192.168.61.100

创建证书目录:

1
2
mkdir -p /home/registry/certs
mkdir -p /home/registry/data 

生成自签名证书:

1
2
3
4
5
cd /home/registry/certs

openssl req \
     -newkey rsa:2048 -nodes -keyout domain.key \
     -x509 -days 3650 -out domain.crt

根据提示引导,输入信息创建证书:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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]:CN
State or Province Name (full name) []:Beijing
Locality Name (eg, city) [Default City]:Beijing
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:192.168.61.100

查看创建的证书和私钥:

1
2
3
4
ls
domain.crt  domain.key

openssl x509 -text -noout -in domain.crt

运行registry容器

1
2
3
4
5
6
docker run -d -p 5000:5000 --restart=always --name registry \
  -v /home/registry/certs:/certs \
  -v /home/registry/data:/var/lib/registry \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \
  registry:2

将domain.cert拷贝到每个docker所在主机的/etc/docker/certs.d/192.168.61.100:5000/ca.crt

1
2
mkdir -p /etc/docker/certs.d/192.168.61.100:5000
cp domain.crt /etc/docker/certs.d/192.168.61.100:5000/ca.crt

重启docker:

1
systemctl restart docker

测试pull和push:

1
2
3
4
5
6
7
8
9
docker pull alpine
docker tag alpine 192.168.61.100:5000/alpine

docker push 192.168.61.100:5000/alpine

docker rmi 192.168.61.100:5000/alpine
docker rmi alpine

docker pull 192.168.61.100:5000/alpine

开启basic认证

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
mkdir -p /home/registry/auth
cd /home/registry/auth

docker run --entrypoint htpasswd registry:2 -Bbn testuser testpassword > htpasswd

docker stop registry
docker rm registry

docker run -d -p 5000:5000 --restart=always --name registry \
  -v /home/registry/auth:/auth \
  -e "REGISTRY_AUTH=htpasswd" \
  -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" \
  -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \
  -v /home/registry/certs:/certs \
  -v /home/registry/data:/var/lib/registry \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \
  registry:2

验证login,push

1
2
3
4
5
6
docker login 192.168.61.100:5000
Username: testuser
Password:
Login Succeeded

docker push 192.168.61.100:5000/alpine

参考