在阿里云上使用Docker部署静态站点
maiaimei 2022/3/26  DockerNginx
记录下在阿里云上使用Docker部署静态站点,支持HTTPS访问。
# 准备工作
# 创建多个目录
# -p 一次性创建层级目录,如果目录存在,则不创建
mkdir -p /opt/nginx /opt/nginx/config/conf.d /opt/nginx/html /opt/nginx/ssl
 1
2
2
# 创建配置文件 - nginx.conf
vim /opt/nginx/nginx.conf
 1
添加以下内容
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;
    
    fastcgi_intercept_errors on;
    include /etc/nginx/conf.d/*.conf;
}
 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
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
# 创建配置文件 - default.conf
vim /opt/nginx/config/conf.d/default.conf
 1
添加以下内容
server {
    listen 80;
    server_name maiamy.cn www.maiamy.cn;
    return 301 https://$host$request_uri;
}
server {
	listen       443 ssl;
	server_name  maiamy.cn www.maiamy.cn;
	ssl_certificate      /ssl/cert.pem; 
	ssl_certificate_key  /ssl/cert.key;
	ssl_session_cache    shared:SSL:1m;
	ssl_session_timeout  5m;
	ssl_ciphers  HIGH:!aNULL:!MD5;
	ssl_prefer_server_ciphers  on;
	
	# 解决:中文乱码
	charset utf-8;
	
	error_page   404  /404.html;
	error_page   500 502 503 504  /50x.html;
	location / {
		root  /usr/share/nginx/html;
		index  index.html index.htm;
	}
}
 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
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
# 上传静态页面
将静态页面上传到/opt/nginx/html
# 上传SSL证书
阿里云免费证书创建步骤:
搜索“SSL 证书”
点击“SSL 证书(应用安全)”
点击“SSL 证书”
点击“免费证书”
点击“创建证书”,按提示输入相关内容
下载刚刚创建成功的证书
重命名证书,与default.conf配置一致
xxx.key 改为 cert.key,对应default.conf的ssl_certificate_key
xxx.pem 改为 cert.pem,对应default.conf的ssl_certificate
将cert.key和cert.pem上传到
/opt/nginx/ssl

如果SSL证书过期,则按1-8步骤操作,将新证书覆盖旧证书。然后重启容器即可。
docker ps # 先停止容器再启动容器 docker stop container_id docker start container_id # 或者重新启动容器 docker restart container_id1
2
3
4
5
6
# 启动容器
docker pull nginx
docker run --name nginx \
-v /opt/nginx/nginx.conf:/etc/nginx/nginx.conf \
-v /opt/nginx/config/conf.d/default.conf:/etc/nginx/conf.d/default.conf \
-v /opt/nginx/html:/usr/share/nginx/html \
-v /opt/nginx/ssl:/ssl \
--network=host \
-d nginx
 1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9