使用 mkcert 製作本機憑證
mkcert 是一個建立本機 TLS 憑證的懶人包工具。本機測試大多用 HTTP 就夠了,但有些情境還是需要使用 HTTPS(如串接第三方的 OAuth2 服務),這時,就會需要這個工具來協助建立本機憑證。
安裝
mkcert 支援 Windows、Linux 與 MacOS。MacOS 可以使用 Homebrew 安裝:
$ brew install mkcert
接著初始化安裝目錄,emoji 用好用滿:
$ mkcert -install
Created a new local CA at "/Users/***/Library/Application Support/mkcert" 💥
Sudo password:
The local CA is now installed in the system trust store! ⚡️
Warning: "certutil" is not available, so the CA can't be automatically installed in Firefox! ⚠️
Install "certutil" with "brew install nss" and re-run "mkcert -install" 👈
The local CA is now installed in Java's trust store! ☕️
Oops!它說要安裝 nss 後再重跑一次,才能裝到 Firefox。
$ brew install nss
$ mkcert -install
Using the local CA at "/Users/***/Library/Application Support/mkcert" ✨
The local CA is already installed in the system trust store! 👍
The local CA is now installed in the Firefox trust store (requires browser restart)! 🦊
The local CA is already installed in Java's trust store! 👍
本機產的證書就會放在 /Users/***/Library/Application Support/mkcert
這個目錄裡:
$ ls /Users/***/Library/Application Support/mkcert
rootCA-key.pem rootCA.pem
新增憑證
接著要新增憑證,直接拿 localhost 來試看看:
$ mkcert localhost
Using the local CA at "/Users/***/Library/Application Support/mkcert" ✨
Created a new certificate valid for the following names 📜
- "localhost"
The certificate is at "./localhost.pem" and the key at "./localhost-key.pem" ✅
它會產生 localhost.pem
與 localhost-key.pem
,這應該就是 Web server 所需要的給的證書,接著來使用 Docker Nginx 試著給它看看
首先先準備 nginx 的設定檔 nginx.conf
:
server { |
接著再啟動 Nginx 的 container:
$ docker run -v `pwd`/localhost-key.pem:/etc/mkcert/localhost-key.pem -v `pwd`/localhost.pem:/etc/mkcert/localhost.pem -v `pwd`/nginx.conf:/etc/nginx/conf.d/default.conf --rm -it -p 443:443 nginx:alpine
因為是直接綁 localhost,所以不需要再新增 /etc/hosts
的內容,直接 curl 即可:
$ curl https://localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
照以上做法,Docker Nginx 可以用之後,即可利用 Nginx reverse proxy 的功能轉到其他 Application,感覺蠻方便的。
其他用法
參考 mkcert --help
,新增憑證的時候,可以新增多個網域:
$ mkcert example.com myapp.dev localhost 127.0.0.1 ::1
Generate "example.com+4.pem" and "example.com+4-key.pem".
也可以新增 wildcard 網域:
$ mkcert "*.example.it"
Generate "_wildcard.example.it.pem" and "_wildcard.example.it-key.pem".