将CppReference离线包通过Docker运行NGINX部署到本地

一、下载离线包

下载地址:cppreference.com

将离线包html-zh-book-20221231.zip下载到~/site/mirror.cppreference.com/,并解压出html-zh-book-20221231/

二、写Nginx配置文件

~/site/mirror.cppreference.com/default.conf写入:

default.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
server {
listen 80;
listen [::]:80;
server_name localhost;

location = / {
return 302 http://$http_host/reference/zh/index.html;
# DO NOT USE THIS!!!
# return 302 /reference/zh/index.html;
}

location / {
# 这是NGINX容器中网站的挂载路径,不是主机的路径
root /usr/share/nginx/html/html-book-20221231;
try_files $uri $uri/ =404;
}

#error_page 404 /404.html;

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

由于index.html不在根目录,所以需要增加跳转:

1
2
3
location = / {
return 302 http://$http_host/reference/zh/index.html;
}

上述代码的作用是在访问网站根目录时,即匹配到/时,跳转到实际地址。如果写的不是location = /,可能出现循环跳转的问题。

不使用相对地址的原因是:根据NGINX的配置文件,自动生成的地址端口是80而非docker映射的端口60080,因此需要使用客户端请求头里的Host字段来确定地址。可以运行

1
2
3
4
5
6
7
8
$ curl -I http://localhost:60080/
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.28.0
Date: Tue, 17 Jun 2025 17:40:16 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: http://localhost:60080/reference/zh/index.html

来查看跳转地址。

三、写Docker Compose文件并启动容器

~/site/mirror.cppreference.com/docker-compose.yml写入:

docker-compose.yml
1
2
3
4
5
6
7
8
9
services:
nginx:
image: "nginx:stable"
ports:
- "60080:80"
volumes:
- ~/site/mirror.cppreference.com/html-book-20221231:/usr/share/nginx/html/html-book-20221231:ro
- ~/site/mirror.cppreference.com/default.conf:/etc/nginx/conf.d/default.conf:ro
restart: always

该文件中定义了主机访问的端口号、网站文件和配置文件的挂载地址。

运行

1
docker compose up -d

启动容器。

四、启动容器

打开localhost:60080观察是否正常运行。