nginx / docker / 本地主机的 ssl

nginx / docker / ssl for localhost

我想为本地主机启用 ssl,使用 nginx 和自签名证书。 我想这样做是因为我将 nginx 作为反向代理放在一个使用 https 重定向的应用程序前面,我不想修改应用程序

我已经使用以下命令生成了证书:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout nginx-selfsigned.key -out nginx-selfsigned.crt

这是我的docker撰写

version: '2.1'
services:

  nginx-proxy:
    image: jwilder/nginx-proxy
    container_name: nginx-proxy
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./data/nginx/certs:/etc/nginx/certs
      - ./data/nginx/nginx.conf:/etc/nginx/nginx.conf
    networks:
     - no-internet
     - internet
    depends_on:
      - ap-service


  back-service:
    ...
    networks:
     - no-internet


  db-service:
    ...
    networks:
     - no-internet
     - internet

networks:
  internet:
    driver: bridge
  no-internet:
    internal: true
    driver: bridge

这是我的 nginx.conf

events {
  worker_connections  1024;  ## Default: 1024
}

http{
    server {
       listen 80;
       listen [::]:80;

       server_name localhost;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $remote_addr;

       location / {
           proxy_pass http://back-service:8080/;
       }
     }

    server {
       listen 443;
       listen [::]:443;

       server_name localhost;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $remote_addr;

       location / {
           proxy_pass http://back-service:8080/;
       }
     }

    server {
       listen 8000;
       listen [::]:8000;

       server_name localhost;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $remote_addr;

       location / {
           proxy_pass http://back-service:8000/;
       }
     }
}

但是当重定向到 https://localhost/ google chrome 时,它会显示一个灰色页面,上面写着 ERR_SSL_PROTOCOL_ERROR

nginx 日志显示如下

nginx-proxy    | nginx.1    | 172.21.0.1 - - [02/Jun/2021:21:54:07 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03\xA4\xF3\xD75\xE13XqtL\xBF\xF5h\x11\x0B\x83\xB55P\xAF\xD1U\x9F\xD3\x17\x9A\xB3\x22}dZ\xE7 \x92\x89\x805\x14L\xE8=\xDAL\xF0\xA0\xBF\xE1\x9A \xC1\xAF\xB4\xC6\xFA\xC7n\xA5.\xBFxK\xAA\xFB\x050\x00\x22ZZ\x13\x01\x13\x02\x13\x03\xC0+\xC0/\xC0,\xC00\xCC\xA9\xCC\xA8\xC0\x13\xC0\x14\x00\x9C\x00\x9D\x00/\x005\x00" 400 158 "-" "-"

您必须在 nginx.conf 上的 server 块中添加证书:

    server {
       listen 443 ssl;

       server_name localhost;
       ssl_certificate     /etc/nginx/certs/nginx-selfsigned.crt;
       ssl_certificate_key /etc/nginx/certs/nginx-selfsigned.key;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $remote_addr;

       location / {
           proxy_pass http://back-service:8080/;
       }
     }