Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
OpenSSL routine for custom Docker API TLS keys (Written for Windows MSYS, but works everywhere)
#!/usr/bin/env bash
set -e
set -o errexit
: "${myPassword:=moin}"
: "${dockerApiIp:=}"
: "${dockerApiPort:=2375}"
: "${altNames:=DNS:jaidPc,DNS:jaid-pc,,,DNS:localhost,IP:}"
: "${daysValid:=3653}"
: "${rsaBits:=4096}"
: "${countryCode:=DE}"
: "${portainer:=}"
# Generating
# Based on
printf %s "$myPassword" >"passphrase.txt"
openssl genrsa -aes256 -passout file:passphrase.txt -out ca-key.pem $rsaBits
MSYS_NO_PATHCONV=1 openssl req -new -x509 -days $daysValid -key ca-key.pem -sha256 -subj "/C=$countryCode/CN=$dockerApiIp:$dockerApiPort" -passin file:passphrase.txt -out ca.pem
openssl genrsa -out server-key.pem $rsaBits
openssl req -subj "/C=$countryCode/CN=$dockerApiIp:$dockerApiPort" -sha256 -new -key server-key.pem -out server.csr
printf %s "subjectAltName = IP:$dockerApiIp,$altNames" >extfile.cnf
openssl x509 -req -days $daysValid -sha256 -in server.csr -passin file:passphrase.txt -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf
openssl genrsa -out key.pem $rsaBits
MSYS_NO_PATHCONV=1 openssl req -subj '/CN=client' -new -key key.pem -out client.csr
printf %s 'extendedKeyUsage = clientAuth' >extfile-client.cnf
openssl x509 -req -days $daysValid -sha256 -in client.csr -passin file:passphrase.txt -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile-client.cnf
# Cleaning
mkdir -p {etc,server,client,shared}
mv {client.csr,server.csr,extfile.cnf,extfile-client.cnf,ca-key.pem,passphrase.txt} etc
mv {server-cert.pem,server-key.pem} server
mv {cert.pem,key.pem} client
mv ca.pem shared
# This file gets generated only on Windows
if [ -f ]; then
mv etc
# Testing
openssl x509 -text -noout -in server/server-cert.pem
# Portainer
# Portainer v2.14.0 expects exactly these filenames and will not work otherwise for some reason
if [ -n "$portainer" ]; then
echo "Portainer support enabled"
mkdir portainer
cp shared/ca.pem portainer/ca.crt
cp client/cert.pem portainer/certificate.crt
cp client/key.pem portainer/key.crt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment