一、生成密钥
1、在Linux服务器上建一个目录,进入此目录,我这里是/root/docker
创建根证书RSA私钥(需要输入密码):
openssl genrsa -aes256 -passout pass:123456 -out ca-key.pem 4096
2、生成CA秘钥文件ca-key.pem;
以此秘钥创建CA证书,自己给自己签发证书,自己就是CA机构,也可以交给第三方机构去签发(需要输入密码):
openssl req -new -x509 -passin pass:123456 -days 1000 -key ca-key.pem -sha256 -subj "/CN=*" -out ca.pem
3、 创建服务端私钥:
openssl genrsa -out server-key.pem 4096
4、生成服务端证书签名请求(csr即certificate signing request,里面包含公钥与服务端信息)
openssl req -passin pass:123456 -subj "/CN=*" -sha256 -new -key server-key.pem -out server.csr
5、生成签名过的服务端证书(需修改IP地址):
echo subjectAltName = DNS:*,IP:xxx.xxx.xxx.xxx,IP:127.0.0.1 >> extfile.cnf
echo extendedKeyUsage = serverAuth >> extfile.cnf
openssl x509 -req -passin pass:123456 -days 1000 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf
6、生成客户私钥:
openssl genrsa -out key.pem 4096
7、生成客户端证书签名请求:
openssl req -passin pass:123456 -subj '/CN=client' -new -key key.pem -out client.csr
8、 生成名为extfile.cnf的配置文件:
echo extendedKeyUsage = clientAuth > extfile-client.cnf
9、复制生成签名过的客户端证书,并设置权限:
openssl x509 -req -passin pass:123456 -days 1000 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile-client.cnf
rm -f client.csr server.csr extfile.cnf extfile-client.cnf
chmod -v 0400 ca-key.pem key.pem server-key.pem
10.一步搞定
需修改第5行IP地址
openssl genrsa -aes256 -passout pass:123456 -out ca-key.pem 4096
openssl req -new -x509 -passin pass:123456 -days 1000 -key ca-key.pem -sha256 -subj "/CN=*" -out ca.pem
openssl genrsa -out server-key.pem 4096
openssl req -passin pass:123456 -subj "/CN=*" -sha256 -new -key server-key.pem -out server.csr
echo subjectAltName = DNS:*,IP:xxx.xxx.xxx.xxx,IP:127.0.0.1 >> extfile.cnf
echo extendedKeyUsage = serverAuth >> extfile.cnf
openssl x509 -req -passin pass:123456 -days 1000 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf
openssl genrsa -out key.pem 4096
openssl req -passin pass:123456 -subj '/CN=client' -new -key key.pem -out client.csr
echo extendedKeyUsage = clientAuth > extfile-client.cnf
openssl x509 -req -passin pass:123456 -days 1000 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile-client.cnf
rm -f client.csr server.csr extfile.cnf extfile-client.cnf
chmod -v 0400 ca-key.pem key.pem server-key.pem
二、设置docker配置
Docker的TLS连接设置打开文件/lib/systemd/system/docker.service:
修改ExecStart行
vim /lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --tlsverify --tlscacert=/root/docker/ca.pem --tlscert=/root/docker/server-cert.pem --tlskey=/root/docker/server-key.pem -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock
三、客户端复制三个文件
key.pem,cert.pem,ca.pem
运行命令如下:
docker --tlsverify --tlscacert=/root/docker/ca.pem --tlscert=/root/docker/cert.pem --tlskey=/root/docker/key.pem -H tcp://device01:2376 version