static-web-docker/README.md
2025-12-25 17:26:32 +08:00

109 lines
3.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 项目说明
本项目用于构建通用的静态web服务docker模版纯静态web服务可以使用本项目产出的docker镜像快速搭建稳定的线上服务。
### 原理说明
每次创建新 tag 时触发工作流,同时发布 tag名和latest两个镜像版本到gitea自动的docker管理平台。
使用Dockerfile构建基于nginx的镜像具体使用中可以宿主机 default.conf / nginx 工作目录到宿主机,宿主机只需要首次部署时构建 docker-compose后续部署只需替换nginx目录即可。
### 用法说明
#### 设计约束
- 基础镜像nginx:alpine体积小
- 不考虑 TLSHTTPS 请由外部反向代理/网关处理)
- 站点内容不随镜像打包,运行时挂载 `./site` 到容器 `/usr/share/nginx/html`
#### 目录结构
```
.
├─ Dockerfile
├─ nginx/
│ └─ default.conf # Nginx 静态站点配置(可按项目调整)
├─ example/
│ ├─ docker-compose.yml # 本地/线上均可复用的示例
│ └─ site/ # 示例静态资源(仅本地验证用)
└─ .gitea/workflows/
└─ build.yml # 基于 tag 的构建与推送
```
#### 本地构建镜像
```bash
docker build -t static-web:latest .
```
#### 使用 docker 命令启动服务
```bash
# 在仓库根目录下准备你的站点目录
mkdir -p site && echo '<h1>Hello</h1>' > site/index.html
docker run -d \
--name static-web \
-p 8080:80 \
-v "$(pwd)/nginx":/etc/nginx/conf.d:ro \
-v "$(pwd)/site":/usr/share/nginx/html:ro \
static-web:latest
# 访问: http://localhost:8080
```
#### 使用 docker-compose.yml 命令启动服务
```bash
cd example
# 可直接使用示例站点example/site/index.html
docker compose up -d
# 访问: http://localhost:8080
```
### 版本与发布
- 推荐使用语义化标签发布:例如 `v1.0.0``v1.0.1`
- 推送 tag 后CI 会构建并推送两个镜像标签:`<tag>``latest`
### CI/CDGitea Actions
工作流文件:`.gitea/workflows/build.yml`
- 触发条件push tag匹配 `v*`)。
- 必需 secrets在仓库设置中配置
- `REGISTRY_HOST`Docker Registry 主机(例如 `registry.example.com`)。
- `REGISTRY_USERNAME` / `REGISTRY_PASSWORD`:用于登录 Registry 的凭据。
- `REGISTRY_IMAGE`:完整镜像名(例如 `registry.example.com/org/static-web`)。
- Runner 需具备 Docker 执行环境;`runs-on` 使用的标签可按你的 Runner 调整。
本地验证镜像成功推送后,线上 `docker-compose.yml` 可使用远程镜像:
```yaml
services:
web:
image: registry.example.com/org/static-web:latest
ports:
- "8080:80"
volumes:
- ./nginx:/etc/nginx/conf.d:ro
- ./site:/usr/share/nginx/html:ro
```
### Nginx 配置要点
- 根目录:`/usr/share/nginx/html`(通过卷挂载提供内容)。
- Gzip对 CSS/JS/JSON/SVG 等启用压缩。
- 缓存对静态资源js/css/img/fonts设置长缓存HTML 禁止缓存。
- 安全:默认开启 `X-Content-Type-Options``X-Frame-Options``Referrer-Policy``CSP` 默认注释,如需请按项目定制。
- SPA 场景:若需前端路由降级到 `index.html`,可将 `location /` 中的 `try_files` 调整为 `try_files $uri /index.html;`
### 常见问题
- 端口冲突:修改 `-p 8080:80` 映射或释放宿主机端口。
- 权限问题:确保宿主机 `./nginx``./site` 对 Runner/部署主机可读;挂载只读可避免误改。
- 缓存过期:生产环境建议为静态资源加内容哈希;或调整 `Cache-Control` 策略。
- CI 无法登录 Registry核对 `REGISTRY_HOST`、用户名/密码与网络可达性Runner 需具备 `docker login` 能力。