docker nginx 配置https

1 前置設(shè)置

# 獲取nginx 1.15版本鏡像(版本自行替換吧)
docker pull nginx:1.15

# 創(chuàng)建nginx掛在目錄
mkdir -p {/data/nginx/{logs,cert}}

# 跑起nginx容器,用于獲取配置文件
docker run --name nginx -d nginx:1.15

# 拷貝nginx配置文件
docker cp  nginx:/etc/nginx/conf.d /data/nginx
docker cp  nginx:/etc/nginx/nginx.conf /data/nginx

# 刪除容器
docker stop nginx && docker rm nginx

2 生成ssl證書

cd /data/nginx/cert

# 生成私鑰
openssl genrsa -out nginx.key

#生成證書(公鑰)
openssl req -new -x509 -key nginx.key -out nginx.crt 

ps:可以使用免費的let's encrypt證書,也可以使用云服務(wù)商提供的證書

3 配置https

# 編輯配置文件
vim /data/nginx/conf.d/

配置文件內(nèi)容(需要修改部分已備注)

server {
    listen       80;
    server_name  localhost; # 換成自己的host
    
    # http請求重定向到https上
    rewrite  ^(.*)$  https://${server_name}$1  permanent;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    #eeee
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

# 增加https部分設(shè)置
server {

   listen  443 ssl;
   server_name  localhost; # 換成自己的host

   ssl_certificate  /etc/nginx/cert/nginx.crt;             #指定證書位置(通過目錄掛載到容器內(nèi)部)
   ssl_certificate_key  /etc/nginx/cert/nginx.key;         #指定私鑰位置(通過目錄掛載到容器內(nèi)部)

   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;
    }

}

4 啟動nginx

docker run --name nginx -d \
-p 80:80 \
-p 443:443 \
-v /data/nginx/cert:/etc/nginx/cert \
-v /data/nginx/nginx.cof:/etc/nginx/nginx.conf \
-v /data/nginx/conf.d:/etc/nginx/conf.d \
nginx:1.15

5 測試訪問

https.png

通過80端口訪問,自動跳轉(zhuǎn)到https的443端口

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容