用docker创建nginx,自动申请免费的域名证书,并且配置重定向或反向代理

chenliang    2023-3-29

 

环境搭建


重裝

bash <(wget --no-check-certificate -qO- 'https://raw.githubusercontent.com/MoeClub/Note/master/InstallNET.sh') -d 11 -v 64 -p lion123 -port 22 

更新环境
apt update -y && apt upgrade -y && apt install -y curl wget sudo socat
安装 Docker

curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh

curl -L "https://github.com/docker/compose/releases/download/v2.16.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose 

chmod +x /usr/local/bin/docker-compose

搭建nginx
创建nginx目录结构

mkdir -p /home/nginx touch /home/nginx/nginx.conf mkdir -p /home/nginx/certs
方法1
申请证书

curl https://get.acme.sh | sh ~/.acme.sh/acme.sh --register-account -m xxxx@gmail.com ~/.acme.sh/acme.sh --issue -d svvv.cn --standalone
下载证书
~/.acme.sh/acme.sh --installcert -d svvv.cn --key-file /home/nginx/certs/key.pem --fullchain-file /home/nginx/certs/cert.pem
方法2
创建SSL证书,我是用CF的15年证书

打开cloudflare官网-进入域名管理-SSL/TLS-源服务器-创建证书
公钥
cd /home/nginx/certs && nano cert.pem
私钥
cd /home/nginx/certs && nano key.pem
进入目录编辑文件
cd /home/nginx/ && nano nginx.conf
重定向配置,跳转到域名
events { worker_connections 1024; } http { server { listen 80; server_name a.svvv.cn; return 301 https://www.baidu.com$request_uri; } server { listen 443 ssl http2; server_name a.svvv.cn; ssl_certificate /etc/nginx/certs/cert.pem; ssl_certificate_key /etc/nginx/certs/key.pem; return 301 https://www.baidu.com$request_uri; } }
反向代理配置,代理指定IP加端口
events { worker_connections 1024; } http { client_max_body_size 1000m; #上传限制参数1G以内文件可上传 server { listen 80; server_name b.svvv.cn; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name b.svvv.cn; ssl_certificate /etc/nginx/certs/cert.pem; ssl_certificate_key /etc/nginx/certs/key.pem; location / { proxy_pass http://127.0.0.1:5212; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } }
代理静态网页的配置方式
events { worker_connections 1024; } server { listen 80; server_name c.svvv.cn; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name c.svvv.cn; ssl_certificate /etc/nginx/certs/cert.pem; ssl_certificate_key /etc/nginx/certs/key.pem; charset utf-8; # 添加这行来指定编码 location / { root /usr/share/nginx/html; index index.html; } }
部署容器
docker run -d --name nginx -p 80:80 -p 443:443 -v /home/nginx/nginx.conf:/etc/nginx/nginx.conf -v /home/nginx/certs:/etc/nginx/certs -v /home/nginx/html:/usr/share/nginx/html nginx:latest
查看运行状态
docker ps -a
开机自启动
docker update --restart=always nginx




首页    阅读 2791