connect to Docker Swarm cluster via remote api

因為當你安裝好 docker 的時候,預設是不會開始 remote api 服務的,只能本機連線,所以第一步必須開起遠端連線的功能,同時為了安全性,需要使用憑證。

  • 建立 ca 憑證
$> openssl genrsa -aes256 -out ca-key.pem 4096 
$> openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
  • 建立 server 憑證

建立 server 憑證, 需要用 server 的 dns 和 server ip (記得把 $host 換成你的)

$> openssl genrsa -out server-key.pem 4096
$> openssl req -subj "/CN=$host" -sha256 -new -key server-key.pem -out server.csr
$> echo subjectAltName = DNS:$host,IP:192.168.0.1 >> extfile.cnf
$> echo extendedKeyUsage = serverAuth >> extfile.cnf
$> openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out server-cert.pem -extfile extfile.cnf
$> rm -rf extfile.cnf
  • 建立 client 憑證
$> openssl genrsa -out key.pem 4096
$> openssl req -subj '/CN=client' -new -key key.pem -out client.csr
$> echo extendedKeyUsage = clientAuth >> extfile.cnf
$> openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out cert.pem -extfile extfile.cnf
$> rm -v client.csr server.csr
  • 把 server 憑證 copy 到 /etc/docker
cp {ca,server-key,server-cert}.pen /etc/docker
  • 修改docker的配置文件
nano /etc/docker/daemon.json 

改成

{
  "hosts": [
    "unix:///var/run/docker.sock",
    "tcp://0.0.0.0:2376"
  ],
  "tlscacert": "/etc/docker/ca.pem",
  "tlscert": "/etc/docker/server-cert.pem",
  "tlskey": "/etc/docker/server-key.pem",
  "tlsverify": true
}

重啟 docker engine

systemctl restart docker
Reference:

https://docs.docker.com/engine/security/https/#create-a-ca-server-and-client-keys-with-openssl