dockerd远程访问和证书配置#

systemd现在广泛被使用,假设docker服务是通过systemd启动的。

docker的systemd配置在:

/lib/systemd/system/docker.socket
/lib/systemd/system/docker.service
  1. ExecStart=/usr/bin/dockerd这一行替换为ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock -H tcp://xxx.xxx.xxx:xxx 填上自己的ip和端口

  2. sytemd重启docker(注意容器都会停止) sudo systemctl daemon-reload sudo systemctl restart docker.service

这样已经可以通过ip端口来远程访问了 例如

   docker -H tcp://xxx.xxx.xxx:xxx images
   curl http://xxx.xxx.xxx:xxx/version

裸连不安全。需要验证客户端。#

参考官网 https://docs.docker.com/engine/security/https/

生成证书和key的步骤:

  1. openssl genrsa -aes256 -out ca-key.pem 4096 生成ca的key。输入密码。得到ca-key.pem

  2. openssl req -new -x509 -days 2000 -key ca-key.pem -sha256 -out ca.pem -subj "/CN=hz" 创建自签署ca证书。输入刚才的密码。得到ca.pem

  3. 创建server用的cert和key (如果只需认证客户端的合法性,可以跳过server端cert和key的创建,从8开始) openssl genrsa -out server-key.pem 4096 生成server的key

  4. openssl req -sha256 -new -key server-key.pem -out server.csr -subj "/CN=hz" 创建证书签名请求文件csr。得到server.csr

  5. echo subjectAltName = IP:0.0.0.0 > extfile.cnf

  6. echo extendedKeyUsage = serverAuth >> extfile.cnf Set the Docker daemon key’s extended usage attributes to be used only for server authentication:

  7. openssl x509 -req -days 2000 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf 签名。输密码。得到server-cert.pem

  8. 创建client用的cert和key(请求时交给服务器进行验证。只有服务器签名的合法证书才能通过验证) openssl genrsa -out client-key.pem 4096

  9. openssl req -subj '/CN=hz' -new -key client-key.pem -out client.csr

  10. echo subjectAltName = IP:0.0.0.0 > extfile-client.cnf

  11. echo extendedKeyUsage = clientAuth > extfile-client.cnf

  12. openssl x509 -req -days 2000 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -extfile extfile-client.cnf

  13. 修改systemd配置并重启docker 配置生成的ca、客户端的cert和key ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock -H tcp://xxx.xxx.xxx:xxx --tlsverify --tlscacert=/xxx/docker_cert/ca.pem --tlscert=/xxx/docker_cert/client-cert.pem --tlskey=/xxx/docker_cert/client-key.pem


开启–tls后#

docker -H tcp://xxx.xxx.xxx:xxx images

已无法连接,必须要传证书进行验证:

docker --tlsverify --tlscacert=./ca.pem --tlscert=./client-cert.pem --tlskey=./client-key.pem -H tcp://xxx.xxx.xxx:xxx images

http要改为https并传证书:#

例如:python的requests

requests.get(dockerd.address + ':%d/info' % int(dockerd.port), verify = False, cert = (config.DOCKER_CERT_PATH + dockerd.client_cert, config.DOCKER_CERT_PATH + dockerd.client_key))