Docker&Nginx-設置SSL


SSL證書下載

此處從騰訊雲處申請了個免費證書,申請流程很快,幾分鍾便搞定了。

https://console.cloud.tencent.com/ssl

在之前設置映射的路徑處,創建一個文件夾用來保存證書文件

mkdir /docker/nginx/cert

然后將下載的證書上傳並挪動到這個cert文件夾中(此處使用winscp工具直接挪動了),稍后用於Nginx容器使用。

創建容器配置

  1. 創建一個新的容器並配置數據卷,注意端口號增加了443,且增加了證書的數據卷。
docker run \
--name nginxweb \
-p 8080:80 \
-p 443:443 \
-v /docker/nginx/nginx.conf:/etc/nginx/nginx.conf \
-v /docker/nginx/conf/conf.d:/etc/nginx/conf.d \
-v /docker/nginx/www:/usr/share/nginx \
-v /docker/nginx/logs:/var/log \
-v /docker/nginx/cert:/etc/nginx/cert \
-d \
nginx
  1. 更改Nginx.Conf

更改nginx.conf文件配置,增加一個server的塊,增加對443的偵聽和證書位置的配置,此處的位置是容器內的位置,也就是創建容器時指定數據卷那里的位置加上證書信息。

server {
  listen 443;
  server_name aspnetcore.online;
  ssl on;
  ssl_certificate /etc/nginx/cert/1_aspnetcore.online_bundle.crt;
  ssl_certificate_key /etc/nginx/cert/2_aspnetcore.online.key;
  ssl_session_timeout 5m;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
  ssl_prefer_server_ciphers on;
  location / {
        proxy_pass http://119.91.109.91:80/;
        proxy_redirect default;
  }
}
  1. 再次請求,將http替換為https,帶上域名重新訪問,重定向到目標頁中。

圖片

這樣一來,反向代理和Https都設置成功了。

Http轉Https

當希望請求的默認是Https時,輸入Http的請求默認轉換成Https的,則可以加上一個配置,301重定向到Https的請求。

server {
  location / {
    proxy_pass http://119.3.138.127:80/;
    proxy_redirect default;
    #http轉https
    return 301 https://$host$request_uri;
 }
}

這樣一來當發起對Nginx的請求后,會轉換成Https的以及將請求轉發到配置的目標地址。圖片

配置預覽

整個nginx.conf預覽下,默認基礎文件上,只是從28行處注釋,28行處之后增加了反向代理和Https配置

user nginx;
worker_processes auto;

error_log /var/log/nginx/error.log notice;
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 {
      location / {
        proxy_pass http://119.3.138.127:80/;
	proxy_redirect default;
        #http轉https
        #return 301 https://$host$request_uri;
   }
  }

  server {
    listen 443;
    server_name aspnetcore.online;
    ssl on;
    ssl_certificate /etc/nginx/cert/1_aspnetcore.online_bundle.crt;
    ssl_certificate_key /etc/nginx/cert/2_aspnetcore.online.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
    location / {
        proxy_pass http://119.91.109.91:80/;
        proxy_redirect default;
    }
  }
}

如此一來,便完成了SSL證書的綁定。

2021-09-20,望技術有成后能回來看見自己的腳步


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM