突發奇想要搞一個ssl的服務器,然后我就打起了docker的主意,想着能不能搞一個基於Docker的服務器,這樣維護起來也方便一點。
設想
想法是滿足這么幾點:
- .NET Core on Docker
- Let’s Encypt on Docker
- nginx on Docker用於反向代理
- Let’s Encypt證書有效期很短,需要能夠自動更新
nginx與dotnet都提供了docker部署的方案,但是Let’s Encypt的certbot提供的文檔強調了這個方法不是很推薦,主要原因是從其他位置不太方便訪問certbot的證書。當然可以通過volumes映射文件訪問,但是端口80和443的獨立占用也不好解決,或許DNS驗證的方法可行?
這方面我也不是很懂啊,就換一種思路,將nginx和certbot放在一個container,.NET Core單獨放在一個地方。由nginx加載證書並提供反向代理,.NET Core程序提供一個http訪問即可,不需要證書。如果后續續期了,還可以順帶一並處理nginx刷新的事情。
方法
准備
確定你有一個能夠正確解析到主機的域名,假設是yourdomain.com。我這里操作的主機是CentOS 8的,其他發行版,包括windows也應該操作方式類似。
接下來我們先看看兩個單獨都應該怎么配置。
nginx+certbot
首先是制作docker image,選擇一個比較簡單的linux發行版,比如alpine進行。先建立一個Dockerfile
FROM nginx:alpine
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN sed -i 's/http/https/g' /etc/apk/repositories
RUN apk update
RUN apk add certbot certbot-nginx
RUN mkdir /etc/letsencrypt
COPY nginx.conf /etc/nginx/nginx.conf
然后在當前目錄創建一個nginx配置文件
為什么不使用conf.d的網站配置,而是直接修改nginx.conf?由於我想直接使用certbot的--nginx指令直接配置nginx,如果使用了子配置的形式,certbot認不出來。
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
#include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name yourdomain.com;# 注意名稱一定要是你需要驗證的域名
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
然后在當前目錄執行
docker build . -t nginx-certbot --network=host
編譯完成之后,就是運行了,需要打開80端口用於驗證。
docker run -v $(pwd)/letsencrypt:/etc/letsencrypt -d -p 80:80 -p 443:443 nginx-certbot
第一次運行需要手動申請一下新的證書,運行
docker exec -it [你的container_name] sh
進入了交互式界面,繼續執行
certbot --nginx -d yourdomain.com
按照提示一步一步即可完成域名驗證。
然后需要增加一個自動運行的服務,可以使用crond,先增加一條運行任務。
echo "0 0 1 * * /usr/bin/certbot renew --quiet" >> /etc/crontabs/root
具體的crond設置的方法,可以參考其他文章,上面設置每個月1號執行。不能設置太勤,會被block
運行ps,如果crond不在運行,手動運行一下crond即可。
全部完成之后,運行exit退出container的shell。
.NET Core app
首先dotnet new webapp,然后直接build,即可生成一個默認發布在5000端口的app,反向代理需要有一個設置,添加一個請求頭:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
然后執行dotnet publish命令,就可以生成可以發布執行的文件了。(這里可以參考官方的文檔,不是本文重點我就不寫了。)
下一步是制作Dockerfile。
FROM mcr.microsoft.com/dotnet/core/aspnet:3.0 AS runtime
WORKDIR /app
COPY published/* ./
ENTRYPOINT ["dotnet", "dot.dll"]
注:現在dotnet版本不同,可能生成所在的監聽端口也有不同。
整合
掌握了上面的基礎之后,我們需要整合了,
修改nginx.conf
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
# include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://192.168.48.2:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
設置好了之后,還是前面分部的步驟來,就先啟動ASP.NET Core然后再啟動nginx就好了。注意需要提前創建bridge網絡,並將兩個container加入進來,並且將上面的IP設置成對應的IP,要不會導致無法正常轉發。
優化與改進
有的老鐵已經發現了,這種方法比較麻煩,第一次啟動的時候,需要做的事情很多,第二次啟動很多配置也會丟失,而且還要手動創建網絡,有沒有什么好辦法呢?
有兩個地方可以進行優化:
-
crond部分有一個增加自動化任務的工作,我這里使用了echo方法向crond增加記錄,其實完全可以自動化這個步驟並確保這個服務啟動。其實可以將這個內容在build中打包進去,或者也可以使用docker-compose設置啟動的命令。
-
將
nginx.conf
提取出來,以更好服務.NET Core,可以使用volume進行映射,通過本機映射文件的形式進行管理。
按照上面的思路,使用docker-compose
優化一下,首先編寫一個docker-compose.yml
:
version: '3.7'
services:
aspnetcoreapp:
image: aspdot
container_name: "aspnetcoreapp"
networks:
- mynetwork
proxy:
depends_on:
- aspnetcoreapp
image: nginx-cerbot
container_name: "nginxcore"
ports:
- 80:80
- 443:443
command: sh -c "echo '0 0 1 * * /usr/bin/certbot renew --quiet' >> /etc/crontabs/root & crond & nginx -g 'daemon off;'"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./letsencrypt:/etc/letsencrypt
# - ./default.conf:/etc/nginx/conf.d/default.conf
# - ./html/:/usr/share/nginx/html/
- ./logs/:/var/log/nginx/
restart: always
networks:
- mynetwork
networks:
mynetwork:
driver: bridge
注:alpine版本的nginx啟動的cmd默認是nginx -g daemon off;,docker-compose的command段只能覆蓋默認CMD,不能追加,所以需要在命令中最后執行這個才行。另外,這個crond默認在后台不能正常運行,需要在Command命令中指定才能正常觸發執行(在container中只有執行crond -f才能正常工作)。
之后,運行
docker-compose up -d
程序正常運行,然后再按照上面nginx+certbot的操作進行即可,certbot會自動處理nginx的ssl轉換問題,可以看到我的nginx.conf變成了這樣:
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
# include /etc/nginx/conf.d/*.conf;
server {
server_name yourdomain.com;
location / {
proxy_pass http://192.168.48.2:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = yourdomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name yourdomain.com;
return 404; # managed by Certbot
}}
至此,整個系統已經正常運行了。
補充一下,nginx的反向代理模式,可以通過在http設置中增加upstream模式的形式,添加主機名稱;實測過程中,IP可能會變化造成nginx無法訪問,這里可以設置名稱為http://aspnetcoreapp:5000,這就不隨着IP變化而失效了。
FAQ
1. 自動更新證書成功,訪問服務的時候,依然提示證書過期錯誤。
nginx證書如果是手動加載的話,自動更新證書之后,nginx不會自動加載新的證書,只有重新nginx -s reload之后才能正確加載。如果是certbot --nginx的話,后續的renew會自動重新加載nginx配置的。
2. docker build中下載資源出現temporary error錯誤
由於docker的bridge模式導致的,有兩種方案可以處理,可以在build命令中指定--network=host或者直接指定docker全局的DNS。參考這篇文章。
3. 刪除鏡像的時候,提示還有container在引用,無法刪除。
docker ps
顯示並沒有活動的容器,但是容器其實還在的,有幾條命令可以派上用場。
- docker ps -a # 顯示所有容器
- docker stop $(docker ps -a -q) # 停止所有容器
- docker rm $(docker ps -a -q) # 刪除所有容器
通過這幾個命令就可以把殘留的container刪除干凈了。
4. nginx提示502 bad gateway
這里需要提醒一下,由於docker網絡bridge的機制,不同contianer之間是不能使用localhost或者127.0.0.1進行相互訪問的,需要使用到該container的IP(實際上是docker分配的虛擬IP)。可以使用docker inspect [containerId]查看容器分配的ip地址。
5. docker內部container,可以ping通,但是無法訪問端口和端口服務.
這個問題非常詭異,我嘗試了很多天都沒有找到問題,最后竟然通過重啟大法解決了問題,有時候重啟docker都無法解決問題,試試重啟一下系統,reboot命令解決。
6. docker之間container之間無法相互訪問
這種情況一般是防火牆的事,設置一下給docker0的權限就可以了。詳情可以查看這里
sudo iptables -I INPUT -i docker0 -j ACCEPT
firewall-cmd --permanent --zone=trusted --change-interface=docker0
firewall-cmd --reload
參考
- https://serversncode.com/netcore-docker-ssl-reverse-proxy/
- https://blog.tonysneed.com/2019/10/13/enable-ssl-with-asp-net-core-using-nginx-and-docker/
- https://blog.darkthread.net/blog/aspnetcore-with-nginx/
- https://geko.cloud/nginx-and-ssl-with-certbot-in-docker-alpine/
- https://www.thegeekdiary.com/docker-troubleshooting-conflict-unable-to-delete-image-is-being-used-by-running-container/
- https://www.c-sharpcorner.com/article/fun-with-docker-compose-using-net-core-and-nginx/