Docker TLS remote connection-2376

If you want to use TLS to safely access the dockerd 2376 port on the remote server, you need to generate a certificate on the remote server, copy it to the client PC, and then use the certificate to access 2376. You can use the following script to generate a certificate

#related configs

###start create file###
echo "start create file"

#go to the path
cd /opt/docker_ca 
#use aes256 gen the key
openssl genrsa -aes256 -passout pass:$PASSWORD  -out ca-key.pem 4096
#gen ca cert
openssl req -new -x509 -passin "pass:$PASSWORD" -days 365 -key ca-key.pem -sha256 -out ca.pem -subj "/C=$COUNTRY/ST=$STATE/L=$CITY/O=$ORGANIZATION/OU=$ORGANIZATIONAL_UNIT/CN=$SERVER/emailAddress=$EMAIL"

#gen server used private key
openssl genrsa -out server-key.pem 4096
#gen csr
openssl req -subj "/CN=$SERVER" -sha256 -new -key server-key.pem -out server.csr
#white list
sh -c 'echo subjectAltName = IP:'$SERVER',IP: >> extfile.cnf'
#extendedKeyUsage = serverAuth put into extfile.cnf
sh -c 'echo extendedKeyUsage = serverAuth >> extfile.cnf'
#Use the CA certificate, CA key and the above server certificate request file to generate the server self signed certificate
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -passin "pass:$PASSWORD" -\CAcreateserial -out server-cert.pem -extfile extfile.cnf

#Generate client certificate RSA private key file
openssl genrsa -out key.pem 4096
#Generate client certificate request file
openssl req -subj '/CN=client' -new -key key.pem -out client.csr
#Continue setting certificate extension properties
sh -c 'echo extendedKeyUsage = clientAuth >> extfile.cnf'
#Generate client self signed certificate (generated according to the above client private key file and client certificate request file)
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -passin "pass:$PASSWORD" -\CAcreateserial -out cert.pem -extfile extfile.cnf

#Change key permissions
chmod 0400 ca-key.pem key.pem server-key.pem
#Change key permissions
chmod 0444 ca.pem server-cert.pem cert.pem
#Delete useless files
rm client.csr server.csr

echo "Generate file complete"

vim /lib/systemd/system/docker.service
systemctl daemon-reload
systemctl restart docker

Copy ca.pem cert.pem key from docker server PEM these three files to MacOS

The generated certificate file is as follows, and the modification permission is 400

If you do not use a certificate or use the wrong certificate, you cannot access the remote dockerd

Use the correct certificate to access the remote dockerd

docker --tlsverify --tlscacert /Users/lizhe/docker-ca/ca.pem --tlscert /Users/lizhe/docker-ca/cert.pem --tlskey /Users/lizhe/docker-ca/key.pem -H version
Send a Message