docker部署nginx并实现反向代理添加ssl证书

1. docker-compose文件

先不做volumes 启动容器

成功后将容器内目录cp到宿主机再做volume操作

1
2
3
4
5
docker cp nginx:/usr/share/nginx/html  ./ngin/html
docker cp nginx:/usr/share/nginx/key ./nginx/key
docker cp nginx:/var/log/nginx ./nginx/logs
docker cp nginx:/etc/nginx/nginx.conf ./nginx/nginx.conf
docker cp nginx:/etc/nginx/conf.d ./nginx/conf.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
version: '3'
services:
nginx:
restart: always
container_name: nginx
image: registry.cn-hangzhou.aliyuncs.com/zznn/mycentos:nginx-latest
ports:
- 80:80
- 443:443
volumes:
- ./nginx/html:/usr/share/nginx/html
- ./nginx/key:/usr/share/nginx/key
- ./nginx/logs:/var/log/nginx
# 有可能会出现不能挂载,这个时候用手动拷贝配置文件就行
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/conf.d:/etc/nginx/conf.d
environment:
- NGINX_PORT=80
- TZ=Asia/Shanghai
privileged: true

2.nginx配置反向代理 配置文件

将ssl key文件上传到相应目录即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
server {
listen 80;
listen [::]:80;
server_name localhost;

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

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}

server {
listen 443 ssl; #监听443端口
server_name localhost; #域名
root /usr/share/nginx/html; #项目的根目录
index index.html index.htm;
ssl_certificate /usr/share/nginx/key/ssl.crt; #ssl配置文件(注意路径)
ssl_certificate_key /usr/share/nginx/key/ssl_nopass.key; #ssl配置文件(注意路径)
ssl_session_timeout 5m;
#ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
#ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://58.40.166.66:8080;
#index index.html index.htm;
}
error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}