refactor: demo/app-simple 更名为 demo/app
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
bin/
|
||||
obj/
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,2 @@
|
||||
bin/
|
||||
obj/
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>Demo</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,18 @@
|
||||
# 编译阶段:使用编译环境镜像 compile-dotnet6(含 SDK 6.0.427)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet6 AS build
|
||||
WORKDIR /src
|
||||
COPY Demo.csproj ./
|
||||
RUN dotnet restore Demo.csproj
|
||||
COPY . ./
|
||||
RUN dotnet publish Demo.csproj -c Release -o /app/publish --no-restore
|
||||
|
||||
# 运行阶段:使用运行环境镜像 runtime-dotnet6(仅含 ASP.NET Core 运行时 6.0.35)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-dotnet6 AS runtime
|
||||
LABEL MAINTAINER="tianjun@odboy.cn"
|
||||
ENV TimeZone=Asia/Shanghai
|
||||
ENV ASPNETCORE_URLS=http://0.0.0.0:8080
|
||||
ENV DOTNET_RUNNING_IN_CONTAINER=true
|
||||
WORKDIR /home/admin
|
||||
COPY --from=build /app/publish ./
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["dotnet", "Demo.dll"]
|
||||
@@ -0,0 +1,18 @@
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 容器内监听 8080,避免与宿主机其它 80 端口冲突;可用环境变量 ASPNETCORE_URLS 覆盖
|
||||
builder.WebHost.UseUrls(Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://0.0.0.0:8080");
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/", () => Results.Json(new
|
||||
{
|
||||
message = "dotnet6 is running",
|
||||
runtime = Environment.Version.ToString(),
|
||||
os = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
|
||||
time = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss zzz")
|
||||
}));
|
||||
|
||||
app.MapGet("/health", () => Results.Ok("ok"));
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,78 @@
|
||||
# dotnet6 编译 + 运行示例
|
||||
|
||||
演示如何用本目录的两个镜像构建一个 .NET 6 Web 应用:
|
||||
|
||||
| 阶段 | 镜像 | 说明 |
|
||||
|----|-------------------------------------------------------------|-----------------------------|
|
||||
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet6` | 含 SDK 6.0.427(见上级 `Dockerfile`) |
|
||||
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-dotnet6` | 仅含 ASP.NET Core 运行时 6.0.35(见 `image/runtime-dotnet6`) |
|
||||
|
||||
编译环境镜像带 SDK 和整套编译工具链(体积大),只在构建阶段使用;运行阶段只拷贝 `dotnet publish` 的产物,
|
||||
镜像里不带 SDK、源码和中间文件。
|
||||
|
||||
### 示例内容
|
||||
|
||||
```
|
||||
demo/
|
||||
├── Demo.csproj # net6.0 Web 项目
|
||||
├── Program.cs # 最小 Web API:GET / 返回运行时信息,GET /health 健康检查
|
||||
├── Dockerfile # 两阶段构建:compile-dotnet6 -> runtime-dotnet6
|
||||
├── build.sh # 构建镜像(PUSH=1 时同时推送)
|
||||
├── docker-compose.yml # 部署编排(端口 8080,固定 IP 172.26.0.20)
|
||||
├── startup.sh # docker-compose up -d
|
||||
└── shutdown.sh # docker-compose down
|
||||
```
|
||||
|
||||
### 构建与部署
|
||||
|
||||
```shell
|
||||
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet6 .
|
||||
PUSH=1 sh build.sh # 构建并推送
|
||||
sh startup.sh # docker-compose -f docker-compose.yml -p dotnet6-demo up -d
|
||||
```
|
||||
|
||||
访问:
|
||||
|
||||
```shell
|
||||
curl http://127.0.0.1:8080/ # {"message":"dotnet6 is running","runtime":"6.0.35",...}
|
||||
curl http://127.0.0.1:8080/health # ok
|
||||
```
|
||||
|
||||
### 关键点
|
||||
|
||||
**还原与发布分离**:先 `COPY` 只有 `*.csproj` 的一层执行 `dotnet restore`,再 `COPY` 源码 `dotnet publish --no-restore`。
|
||||
源码改动不会让还原缓存失效,重复构建更快。多项目解决方案可按需增加 `COPY` 的 `*.sln` / `*.csproj` 文件。
|
||||
|
||||
**监听地址**:容器内监听 `8080`(`ASPNETCORE_URLS=http://0.0.0.0:8080`),不占用 80 端口,方便与宿主机其它服务共存。
|
||||
镜像环境变量、compose 环境变量、部署时 `-e` 三者依次覆盖。
|
||||
|
||||
**时区**:镜像已内置 `TimeZone=Asia/Shanghai`,`DateTimeOffset.Now` 输出 +08:00;compose 中再用 `TZ` 显式声明一次。
|
||||
|
||||
**入口**:`ENTRYPOINT ["dotnet", "Demo.dll"]`,使用 exec 形式保证 `docker stop` 的 SIGTERM 能传到进程,优雅退出。
|
||||
|
||||
**健康检查**:运行镜像自带 `netstat`(`net-tools`),直接用端口探测,不需要额外安装 curl。
|
||||
|
||||
### 运维命令
|
||||
|
||||
```shell
|
||||
docker logs -f dotnet6-demo # 应用日志(stdout/stderr)
|
||||
docker exec dotnet6-demo dotnet --info # 确认运行时版本
|
||||
docker exec dotnet6-demo sh -c 'ls /home/admin'
|
||||
```
|
||||
|
||||
### 调试时直接在编译镜像里运行
|
||||
|
||||
需要看编译报错或临时跑一下时,可以只挂载源码进编译镜像(不需要构建镜像):
|
||||
|
||||
```shell
|
||||
docker run --rm -it -p 8080:8080 \
|
||||
-v "$PWD":/src -w /src \
|
||||
registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet6 \
|
||||
dotnet run
|
||||
```
|
||||
|
||||
### 停止
|
||||
|
||||
```shell
|
||||
sh shutdown.sh
|
||||
```
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet6}
|
||||
docker build -t "${IMAGE}" .
|
||||
|
||||
if [ "${PUSH:-0}" = "1" ]; then
|
||||
docker push "${IMAGE}"
|
||||
fi
|
||||
@@ -0,0 +1,28 @@
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
dotnet6-demo:
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: "172.26.0.0/24"
|
||||
|
||||
services:
|
||||
demo:
|
||||
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet6 # 镜像由 build.sh 构建
|
||||
container_name: dotnet6-demo
|
||||
restart: unless-stopped
|
||||
ports: # 映射端口
|
||||
- "8080:8080"
|
||||
environment: # 设置环境变量,相当于docker run命令中的-e
|
||||
TZ: Asia/Shanghai
|
||||
ASPNETCORE_URLS: http://0.0.0.0:8080
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "netstat -tln | grep -q ':8080 '"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
networks:
|
||||
dotnet6-demo:
|
||||
ipv4_address: 172.26.0.20
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p dotnet6-demo down
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p dotnet6-demo up -d
|
||||
@@ -0,0 +1,4 @@
|
||||
bin/
|
||||
obj/
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,2 @@
|
||||
bin/
|
||||
obj/
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>Demo</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,18 @@
|
||||
# 编译阶段:使用编译环境镜像 compile-dotnet8(含 SDK 8.0.403)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet8 AS build
|
||||
WORKDIR /src
|
||||
COPY Demo.csproj ./
|
||||
RUN dotnet restore Demo.csproj
|
||||
COPY . ./
|
||||
RUN dotnet publish Demo.csproj -c Release -o /app/publish --no-restore
|
||||
|
||||
# 运行阶段:使用运行环境镜像 runtime-dotnet8(仅含 ASP.NET Core 运行时 8.0.10)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-dotnet8 AS runtime
|
||||
LABEL MAINTAINER="tianjun@odboy.cn"
|
||||
ENV TimeZone=Asia/Shanghai
|
||||
ENV ASPNETCORE_URLS=http://0.0.0.0:8081
|
||||
ENV DOTNET_RUNNING_IN_CONTAINER=true
|
||||
WORKDIR /home/admin
|
||||
COPY --from=build /app/publish ./
|
||||
EXPOSE 8081
|
||||
ENTRYPOINT ["dotnet", "Demo.dll"]
|
||||
@@ -0,0 +1,18 @@
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 容器内监听 8081,避免与宿主机其它 80 端口冲突;可用环境变量 ASPNETCORE_URLS 覆盖
|
||||
builder.WebHost.UseUrls(Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://0.0.0.0:8081");
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/", () => Results.Json(new
|
||||
{
|
||||
message = "dotnet8 is running",
|
||||
runtime = Environment.Version.ToString(),
|
||||
os = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
|
||||
time = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss zzz")
|
||||
}));
|
||||
|
||||
app.MapGet("/health", () => Results.Ok("ok"));
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,78 @@
|
||||
# dotnet8 编译 + 运行示例
|
||||
|
||||
演示如何用本目录的两个镜像构建一个 .NET 8 Web 应用:
|
||||
|
||||
| 阶段 | 镜像 | 说明 |
|
||||
| --- |-------------------------------------------------------------|-----------------------------|
|
||||
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet8` | 含 SDK 8.0.403(见上级 `Dockerfile`) |
|
||||
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-dotnet8` | 仅含 ASP.NET Core 运行时 8.0.10(见 `image/runtime-dotnet8`) |
|
||||
|
||||
编译环境镜像带 SDK 和整套编译工具链(体积大),只在构建阶段使用;运行阶段只拷贝 `dotnet publish` 的产物,
|
||||
镜像里不带 SDK、源码和中间文件。
|
||||
|
||||
### 示例内容
|
||||
|
||||
```
|
||||
demo/
|
||||
├── Demo.csproj # net8.0 Web 项目
|
||||
├── Program.cs # 最小 Web API:GET / 返回运行时信息,GET /health 健康检查
|
||||
├── Dockerfile # 两阶段构建:compile-dotnet8 -> runtime-dotnet8
|
||||
├── build.sh # 构建镜像(PUSH=1 时同时推送)
|
||||
├── docker-compose.yml # 部署编排(端口 8081,固定 IP 172.28.0.20)
|
||||
├── startup.sh # docker-compose up -d
|
||||
└── shutdown.sh # docker-compose down
|
||||
```
|
||||
|
||||
### 构建与部署
|
||||
|
||||
```shell
|
||||
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet8 .
|
||||
PUSH=1 sh build.sh # 构建并推送
|
||||
sh startup.sh # docker-compose -f docker-compose.yml -p dotnet8-demo up -d
|
||||
```
|
||||
|
||||
访问:
|
||||
|
||||
```shell
|
||||
curl http://127.0.0.1:8081/ # {"message":"dotnet8 is running","runtime":"8.0.10",...}
|
||||
curl http://127.0.0.1:8081/health # ok
|
||||
```
|
||||
|
||||
### 关键点
|
||||
|
||||
**还原与发布分离**:先 `COPY` 只有 `*.csproj` 的一层执行 `dotnet restore`,再 `COPY` 源码 `dotnet publish --no-restore`。
|
||||
源码改动不会让还原缓存失效,重复构建更快。多项目解决方案可按需增加 `COPY` 的 `*.sln` / `*.csproj` 文件。
|
||||
|
||||
**监听地址**:容器内监听 `8081`(`ASPNETCORE_URLS=http://0.0.0.0:8081`),不占用 80 端口,方便与宿主机其它服务共存。
|
||||
镜像环境变量、compose 环境变量、部署时 `-e` 三者依次覆盖。
|
||||
|
||||
**时区**:镜像已内置 `TimeZone=Asia/Shanghai`,`DateTimeOffset.Now` 输出 +08:00;compose 中再用 `TZ` 显式声明一次。
|
||||
|
||||
**入口**:`ENTRYPOINT ["dotnet", "Demo.dll"]`,使用 exec 形式保证 `docker stop` 的 SIGTERM 能传到进程,优雅退出。
|
||||
|
||||
**健康检查**:运行镜像自带 `netstat`(`net-tools`),直接用端口探测,不需要额外安装 curl。
|
||||
|
||||
### 运维命令
|
||||
|
||||
```shell
|
||||
docker logs -f dotnet8-demo # 应用日志(stdout/stderr)
|
||||
docker exec dotnet8-demo dotnet --info # 确认运行时版本
|
||||
docker exec dotnet8-demo sh -c 'ls /home/admin'
|
||||
```
|
||||
|
||||
### 调试时直接在编译镜像里运行
|
||||
|
||||
需要看编译报错或临时跑一下时,可以只挂载源码进编译镜像(不需要构建镜像):
|
||||
|
||||
```shell
|
||||
docker run --rm -it -p 8081:8081 \
|
||||
-v "$PWD":/src -w /src \
|
||||
registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet8 \
|
||||
dotnet run
|
||||
```
|
||||
|
||||
### 停止
|
||||
|
||||
```shell
|
||||
sh shutdown.sh
|
||||
```
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet8}
|
||||
docker build -t "${IMAGE}" .
|
||||
|
||||
if [ "${PUSH:-0}" = "1" ]; then
|
||||
docker push "${IMAGE}"
|
||||
fi
|
||||
@@ -0,0 +1,28 @@
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
dotnet8-demo:
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: "172.28.0.0/24"
|
||||
|
||||
services:
|
||||
demo:
|
||||
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet8 # 镜像由 build.sh 构建
|
||||
container_name: dotnet8-demo
|
||||
restart: unless-stopped
|
||||
ports: # 映射端口
|
||||
- "8081:8081"
|
||||
environment: # 设置环境变量,相当于docker run命令中的-e
|
||||
TZ: Asia/Shanghai
|
||||
ASPNETCORE_URLS: http://0.0.0.0:8081
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "netstat -tln | grep -q ':8081 '"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
networks:
|
||||
dotnet8-demo:
|
||||
ipv4_address: 172.28.0.20
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p dotnet8-demo down
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p dotnet8-demo up -d
|
||||
@@ -0,0 +1,4 @@
|
||||
bin/
|
||||
obj/
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,2 @@
|
||||
bin/
|
||||
obj/
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>Demo</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,18 @@
|
||||
# 编译阶段:使用编译环境镜像 compile-dotnet9(含 SDK 9.0.100-rc.2.24474.11)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet9 AS build
|
||||
WORKDIR /src
|
||||
COPY Demo.csproj ./
|
||||
RUN dotnet restore Demo.csproj
|
||||
COPY . ./
|
||||
RUN dotnet publish Demo.csproj -c Release -o /app/publish --no-restore
|
||||
|
||||
# 运行阶段:使用运行环境镜像 runtime-dotnet9(仅含 ASP.NET Core 运行时 9.0.0-rc.2.24474.3)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-dotnet9 AS runtime
|
||||
LABEL MAINTAINER="tianjun@odboy.cn"
|
||||
ENV TimeZone=Asia/Shanghai
|
||||
ENV ASPNETCORE_URLS=http://0.0.0.0:8082
|
||||
ENV DOTNET_RUNNING_IN_CONTAINER=true
|
||||
WORKDIR /home/admin
|
||||
COPY --from=build /app/publish ./
|
||||
EXPOSE 8082
|
||||
ENTRYPOINT ["dotnet", "Demo.dll"]
|
||||
@@ -0,0 +1,18 @@
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 容器内监听 8082,避免与宿主机其它 80 端口冲突;可用环境变量 ASPNETCORE_URLS 覆盖
|
||||
builder.WebHost.UseUrls(Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://0.0.0.0:8082");
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/", () => Results.Json(new
|
||||
{
|
||||
message = "dotnet9 is running",
|
||||
runtime = Environment.Version.ToString(),
|
||||
os = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
|
||||
time = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss zzz")
|
||||
}));
|
||||
|
||||
app.MapGet("/health", () => Results.Ok("ok"));
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,78 @@
|
||||
# dotnet9 编译 + 运行示例
|
||||
|
||||
演示如何用本目录的两个镜像构建一个 .NET 9 Web 应用:
|
||||
|
||||
| 阶段 | 镜像 | 说明 |
|
||||
| --- |-------------------------------------------------------------|-----------------------------|
|
||||
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet9` | 含 SDK 9.0.100-rc.2.24474.11(见上级 `Dockerfile`) |
|
||||
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-dotnet9` | 仅含 ASP.NET Core 运行时 9.0.0-rc.2.24474.3(见 `image/runtime-dotnet9`) |
|
||||
|
||||
编译环境镜像带 SDK 和整套编译工具链(体积大),只在构建阶段使用;运行阶段只拷贝 `dotnet publish` 的产物,
|
||||
镜像里不带 SDK、源码和中间文件。
|
||||
|
||||
### 示例内容
|
||||
|
||||
```
|
||||
demo/
|
||||
├── Demo.csproj # net9.0 Web 项目
|
||||
├── Program.cs # 最小 Web API:GET / 返回运行时信息,GET /health 健康检查
|
||||
├── Dockerfile # 两阶段构建:compile-dotnet9 -> runtime-dotnet9
|
||||
├── build.sh # 构建镜像(PUSH=1 时同时推送)
|
||||
├── docker-compose.yml # 部署编排(端口 8082,固定 IP 172.29.0.20)
|
||||
├── startup.sh # docker-compose up -d
|
||||
└── shutdown.sh # docker-compose down
|
||||
```
|
||||
|
||||
### 构建与部署
|
||||
|
||||
```shell
|
||||
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet9 .
|
||||
PUSH=1 sh build.sh # 构建并推送
|
||||
sh startup.sh # docker-compose -f docker-compose.yml -p dotnet9-demo up -d
|
||||
```
|
||||
|
||||
访问:
|
||||
|
||||
```shell
|
||||
curl http://127.0.0.1:8082/ # {"message":"dotnet9 is running","runtime":"9.0.0-rc.2.24474.3",...}
|
||||
curl http://127.0.0.1:8082/health # ok
|
||||
```
|
||||
|
||||
### 关键点
|
||||
|
||||
**还原与发布分离**:先 `COPY` 只有 `*.csproj` 的一层执行 `dotnet restore`,再 `COPY` 源码 `dotnet publish --no-restore`。
|
||||
源码改动不会让还原缓存失效,重复构建更快。多项目解决方案可按需增加 `COPY` 的 `*.sln` / `*.csproj` 文件。
|
||||
|
||||
**监听地址**:容器内监听 `8082`(`ASPNETCORE_URLS=http://0.0.0.0:8082`),不占用 80 端口,方便与宿主机其它服务共存。
|
||||
镜像环境变量、compose 环境变量、部署时 `-e` 三者依次覆盖。
|
||||
|
||||
**时区**:镜像已内置 `TimeZone=Asia/Shanghai`,`DateTimeOffset.Now` 输出 +08:00;compose 中再用 `TZ` 显式声明一次。
|
||||
|
||||
**入口**:`ENTRYPOINT ["dotnet", "Demo.dll"]`,使用 exec 形式保证 `docker stop` 的 SIGTERM 能传到进程,优雅退出。
|
||||
|
||||
**健康检查**:运行镜像自带 `netstat`(`net-tools`),直接用端口探测,不需要额外安装 curl。
|
||||
|
||||
### 运维命令
|
||||
|
||||
```shell
|
||||
docker logs -f dotnet9-demo # 应用日志(stdout/stderr)
|
||||
docker exec dotnet9-demo dotnet --info # 确认运行时版本
|
||||
docker exec dotnet9-demo sh -c 'ls /home/admin'
|
||||
```
|
||||
|
||||
### 调试时直接在编译镜像里运行
|
||||
|
||||
需要看编译报错或临时跑一下时,可以只挂载源码进编译镜像(不需要构建镜像):
|
||||
|
||||
```shell
|
||||
docker run --rm -it -p 8082:8082 \
|
||||
-v "$PWD":/src -w /src \
|
||||
registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-dotnet9 \
|
||||
dotnet run
|
||||
```
|
||||
|
||||
### 停止
|
||||
|
||||
```shell
|
||||
sh shutdown.sh
|
||||
```
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet9}
|
||||
docker build -t "${IMAGE}" .
|
||||
|
||||
if [ "${PUSH:-0}" = "1" ]; then
|
||||
docker push "${IMAGE}"
|
||||
fi
|
||||
@@ -0,0 +1,28 @@
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
dotnet9-demo:
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: "172.29.0.0/24"
|
||||
|
||||
services:
|
||||
demo:
|
||||
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-dotnet9 # 镜像由 build.sh 构建
|
||||
container_name: dotnet9-demo
|
||||
restart: unless-stopped
|
||||
ports: # 映射端口
|
||||
- "8082:8082"
|
||||
environment: # 设置环境变量,相当于docker run命令中的-e
|
||||
TZ: Asia/Shanghai
|
||||
ASPNETCORE_URLS: http://0.0.0.0:8082
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "netstat -tln | grep -q ':8082 '"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
networks:
|
||||
dotnet9-demo:
|
||||
ipv4_address: 172.29.0.20
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p dotnet9-demo down
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p dotnet9-demo up -d
|
||||
@@ -0,0 +1,6 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
venv/
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,4 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
venv/
|
||||
@@ -0,0 +1,18 @@
|
||||
# 单阶段:runtime-python310 已含 Python 3.10.0 + pip 镜像源(见 image/runtime-python310),编译与运行共用
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-python310
|
||||
LABEL MAINTAINER="tianjun@odboy.cn"
|
||||
ENV TimeZone=Asia/Shanghai
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
ENV APP_PORT=8083
|
||||
WORKDIR /home/admin
|
||||
|
||||
# 先只拷贝依赖清单,依赖不变时复用 pip 层缓存
|
||||
COPY requirements.txt ./
|
||||
RUN pip3 install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY app.py ./
|
||||
COPY templates ./templates
|
||||
|
||||
EXPOSE 8083
|
||||
# exec 形式,保证 docker stop 的 SIGTERM 能传到 python 进程
|
||||
ENTRYPOINT ["python3", "app.py"]
|
||||
@@ -0,0 +1,91 @@
|
||||
# python310-flask 示例
|
||||
|
||||
演示如何用 `runtime-python310` 镜像构建并运行一个 Python 3.10 + Flask Web 应用:
|
||||
|
||||
| 阶段 | 镜像 | 说明 |
|
||||
| --- |-----------------------------------------------------------------|-------------------------------------------------|
|
||||
| 编译 + 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-python310` | 含 Python 3.10.0 与 pip 镜像源(见 `image/runtime-python310`) |
|
||||
|
||||
与 dotnet 示例不同,Python 是解释型语言,不需要单独的编译镜像:`pip install` 与直接运行都在同一个镜像内完成。
|
||||
|
||||
### 示例内容
|
||||
|
||||
```
|
||||
demo/
|
||||
├── app.py # Flask 应用:GET / 运行时信息,GET /health,GET /api/hello/<name>,GET /page 页面
|
||||
├── templates/
|
||||
│ └── index.html # /page 使用的 Jinja2 模板
|
||||
├── requirements.txt # 依赖清单(Flask 3.0.3)
|
||||
├── Dockerfile # 单阶段构建:runtime-python310
|
||||
├── build.sh # 构建镜像(PUSH=1 时同时推送)
|
||||
├── docker-compose.yml # 部署编排(端口 8083,固定 IP 172.30.0.20)
|
||||
├── startup.sh # docker-compose up -d
|
||||
└── shutdown.sh # docker-compose down
|
||||
```
|
||||
|
||||
### 构建与部署
|
||||
|
||||
```shell
|
||||
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-python310-flask .
|
||||
PUSH=1 sh build.sh # 构建并推送
|
||||
sh startup.sh # docker-compose -f docker-compose.yml -p python310-flask-demo up -d
|
||||
```
|
||||
|
||||
访问:
|
||||
|
||||
```shell
|
||||
curl http://127.0.0.1:8083/ # {"message":"python310-flask is running","python":"3.10.0",...}
|
||||
curl http://127.0.0.1:8083/health # ok
|
||||
curl http://127.0.0.1:8083/api/hello/demo # {"message":"Hello, demo!",...}
|
||||
```
|
||||
|
||||
浏览器打开 http://127.0.0.1:8083/page 可看到渲染后的运行信息页面。
|
||||
|
||||
### 关键点
|
||||
|
||||
**依赖层缓存**:先只 `COPY requirements.txt` 执行 `pip install`,再 `COPY` 源码。只改 `app.py` 时不会重装依赖,重复构建更快。
|
||||
基础镜像已预置 `~/.pip/pip.conf` 指向阿里云源,`pip install` 无需额外换源。
|
||||
|
||||
**监听地址**:容器内监听 `8083`(`APP_PORT`),避开 dotnet6/8/9 示例占用的 8080/8081/8082;宿主机映射与容器端口一致。
|
||||
|
||||
**时区**:代码内统一按 UTC+8 输出时间,即使容器 `TZ` 未生效也不会差 8 小时;compose 中用 `TZ` 再显式声明一次。
|
||||
|
||||
**日志**:`PYTHONUNBUFFERED=1` 关闭 stdout 缓冲,`docker logs` 能实时看到请求日志;Flask 日志本身输出到 stderr。
|
||||
|
||||
**入口**:`ENTRYPOINT ["python", "app.py"]`,exec 形式保证 `docker stop` 的 SIGTERM 能传到进程。
|
||||
|
||||
**健康检查**:运行镜像自带 `net-tools`,直接用 `netstat` 探测端口,不需要额外安装 curl。
|
||||
|
||||
### 运维命令
|
||||
|
||||
```shell
|
||||
docker logs -f python310-flask-demo # 应用日志(stdout/stderr)
|
||||
docker exec python310-flask-demo python -V # 确认 Python 版本
|
||||
docker exec python310-flask-demo pip list # 确认依赖版本
|
||||
```
|
||||
|
||||
### 调试时直接在运行镜像里运行
|
||||
|
||||
需要临时改代码看效果时,可以只挂载源码进运行镜像(不需要构建镜像):
|
||||
|
||||
```shell
|
||||
docker run --rm -it -p 8083:8083 \
|
||||
-v "$PWD":/home/admin -w /home/admin \
|
||||
registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-python310 \
|
||||
sh -c 'pip install -r requirements.txt && python app.py'
|
||||
```
|
||||
|
||||
### 生产运行
|
||||
|
||||
示例用 `app.run()` 的内置服务器,便于直接 `python app.py` 演示。生产环境建议换成 WSGI 服务器,
|
||||
例如在 `requirements.txt` 增加 `gunicorn==21.2.0`,入口改为:
|
||||
|
||||
```dockerfile
|
||||
ENTRYPOINT ["gunicorn", "-w", "4", "-b", "0.0.0.0:8083", "app:app"]
|
||||
```
|
||||
|
||||
### 停止
|
||||
|
||||
```shell
|
||||
sh shutdown.sh
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
import os
|
||||
import platform
|
||||
import socket
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import flask
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
# 国内时区 UTC+8,容器内 TZ 即使没生效也能输出正确时间
|
||||
TZ8 = timezone(timedelta(hours=8))
|
||||
START_TIME = datetime.now(TZ8)
|
||||
|
||||
|
||||
def runtime_info():
|
||||
return {
|
||||
"message": "python310-flask is running",
|
||||
"python": platform.python_version(),
|
||||
"flask": flask.__version__,
|
||||
"impl": platform.python_implementation(),
|
||||
"os": platform.platform(),
|
||||
"hostname": socket.gethostname(),
|
||||
"time": datetime.now(TZ8).strftime("%Y-%m-%d %H:%M:%S %z"),
|
||||
"uptime": str(datetime.now(TZ8) - START_TIME).split(".")[0],
|
||||
}
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index():
|
||||
return flask.jsonify(runtime_info())
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return "ok"
|
||||
|
||||
|
||||
@app.get("/api/hello/<name>")
|
||||
def hello(name):
|
||||
return flask.jsonify({"message": f"Hello, {name}!", "time": datetime.now(TZ8).isoformat()})
|
||||
|
||||
|
||||
@app.get("/page")
|
||||
def page():
|
||||
return flask.render_template("index.html", info=runtime_info())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 容器内监听 8083,避免与 dotnet6/8/9 示例的 8080/8081/8082 冲突;可用环境变量 APP_PORT 覆盖
|
||||
port = int(os.environ.get("APP_PORT", "8083"))
|
||||
app.run(host="0.0.0.0", port=port)
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在示例目录下构建示例镜像
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-python310-flask}
|
||||
docker build -t "${IMAGE}" .
|
||||
|
||||
if [ "${PUSH:-0}" = "1" ]; then
|
||||
docker push "${IMAGE}"
|
||||
fi
|
||||
@@ -0,0 +1,29 @@
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
python310-flask-demo:
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: "172.30.0.0/24"
|
||||
|
||||
services:
|
||||
demo:
|
||||
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-python310-flask # 镜像由 build.sh 构建
|
||||
container_name: python310-flask-demo
|
||||
restart: unless-stopped
|
||||
ports: # 映射端口
|
||||
- "8083:8083"
|
||||
environment: # 设置环境变量,相当于docker run命令中的-e
|
||||
TZ: Asia/Shanghai
|
||||
APP_PORT: "8083"
|
||||
healthcheck:
|
||||
# 运行镜像自带 net-tools,直接用端口探测,不额外安装 curl
|
||||
test: ["CMD-SHELL", "netstat -tln | grep -q ':8083 '"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
networks:
|
||||
python310-flask-demo:
|
||||
ipv4_address: 172.30.0.20
|
||||
@@ -0,0 +1,2 @@
|
||||
Flask==3.0.3
|
||||
Werkzeug==3.0.3
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p python310-flask-demo down
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p python310-flask-demo up -d
|
||||
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>python310-flask</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; margin: 40px; color: #333; }
|
||||
table { border-collapse: collapse; min-width: 520px; }
|
||||
th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
|
||||
th { background: #f5f5f5; width: 160px; }
|
||||
a { color: #1677ff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>python310-flask 运行信息</h2>
|
||||
<table>
|
||||
{% for key, value in info.items() %}
|
||||
<tr>
|
||||
<th>{{ key }}</th>
|
||||
<td>{{ value }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
<p>
|
||||
其它接口:<a href="/api/hello/demo">/api/hello/<name></a>、<a href="/health">/health</a>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,3 @@
|
||||
target/
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,3 @@
|
||||
target/
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -0,0 +1,18 @@
|
||||
# 编译阶段:compile-maven3-jdk17(JDK 17 + Maven 3.9.9 + 阿里云 Maven 源)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-maven3-jdk17 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# 先只拷贝 POM 预热依赖层:源码改动不会让依赖缓存失效
|
||||
COPY pom.xml ./
|
||||
RUN mvn -B -q dependency:go-offline
|
||||
|
||||
COPY src ./src
|
||||
RUN mvn -B -q clean package -DskipTests
|
||||
|
||||
# 运行阶段:自建 runtime-tomcat10(runtime-jdk17 + Tomcat 10.1.34,Servlet 6.0 / Jakarta EE 10,对应 Spring 6)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-tomcat10 AS runtime
|
||||
LABEL MAINTAINER="tianjun@odboy.cn"
|
||||
WORKDIR /home/admin
|
||||
# 带版本号的 war 改名后部署,上下文路径 = /spring-war17
|
||||
# 基础镜像已清空 webapps/*,时区、curl、EXPOSE 8080、ENTRYPOINT catalina.sh run 均由基础镜像提供
|
||||
COPY --from=build /src/target/spring-war17.war ${CATALINA_HOME}/webapps/spring-war17.war
|
||||
@@ -0,0 +1,101 @@
|
||||
# spring-war17 示例
|
||||
|
||||
演示如何用 `compile-maven3-jdk17` 打出 **war 包**,再部署到外置 Tomcat 10.1 运行。与
|
||||
[`demo/app-simple/springboot-jar17`](../springboot-jar17/README.md) 对照:应用代码几乎一样,区别只在打包方式与运行容器。
|
||||
|
||||
| 阶段 | 镜像 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-maven3-jdk17` | JDK 17 + Maven 3.9.9 + 阿里云 Maven 源(见 `image/compile-maven3-jdk17`) |
|
||||
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-tomcat10` | 自建镜像:JDK 17 + Tomcat 10.1.34(Servlet 6.0 / Jakarta EE 10,对应 Spring 6),见 `image/runtime-tomcat10` |
|
||||
|
||||
> Spring 6 要求 Jakarta EE 9+,即 **Tomcat 10.1 及以上**;Tomcat 9(`javax.servlet`)跑不了本示例。
|
||||
|
||||
### 示例内容
|
||||
|
||||
```
|
||||
spring-war17/
|
||||
├── pom.xml # packaging=war,Spring 6.2.1 + Thymeleaf 3.1 + Jackson 2.18,不依赖 Boot
|
||||
├── src/main/java/cn/odboy/demo/
|
||||
│ ├── WebAppInitializer.java # 替代 web.xml,注册 DispatcherServlet(映射 /api/*)
|
||||
│ ├── WebConfig.java # @EnableWebMvc + Thymeleaf 视图解析 + Jackson
|
||||
│ ├── DemoController.java # @RestController:/ 、/info、/hello/{name}(在 /api 前缀下)
|
||||
│ └── PageController.java # @Controller:/api/page 渲染模板
|
||||
├── src/main/resources/templates/index.html
|
||||
├── src/main/webapp/WEB-INF/web.xml # 仅声明 metadata-complete=false 与会话超时,无 servlet 映射
|
||||
├── Dockerfile # 两阶段:compile-maven3-jdk17 -> runtime-tomcat10
|
||||
├── build.sh # 构建镜像(PUSH=1 时同时推送)
|
||||
├── docker-compose.yml # 部署编排(8085 -> 容器 8080,固定 IP 172.30.2.20)
|
||||
├── startup.sh # docker-compose up -d
|
||||
└── shutdown.sh # docker-compose down
|
||||
```
|
||||
|
||||
### 构建与部署
|
||||
|
||||
```shell
|
||||
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-spring-war17 .
|
||||
PUSH=1 sh build.sh # 构建并推送
|
||||
sh startup.sh # docker-compose -f docker-compose.yml -p spring-war17-demo up -d
|
||||
```
|
||||
|
||||
war 部署后上下文路径为 **`/spring-war17`**,接口都在该前缀下:
|
||||
|
||||
```shell
|
||||
curl http://127.0.0.1:8085/spring-war17/api/ # {"message":"spring-war17 is running","java":"17.0.x",...}
|
||||
curl http://127.0.0.1:8085/spring-war17/api/info # 同上
|
||||
curl http://127.0.0.1:8085/spring-war17/api/hello/demo
|
||||
```
|
||||
|
||||
浏览器打开 http://127.0.0.1:8085/spring-war17/api/page 可看到渲染后的运行信息页面。
|
||||
|
||||
### 关键点
|
||||
|
||||
**没有 servlet 映射的 web.xml**:`WebAppInitializer` 继承 `AbstractAnnotationConfigDispatcherServletInitializer`,
|
||||
Tomcat 通过 Servlet 3+ 的 `ServletContainerInitializer` 机制自动发现它并注册 DispatcherServlet。
|
||||
`src/main/webapp/WEB-INF/web.xml` 只声明 `metadata-complete="false"` 和会话超时,不写任何 servlet 映射;
|
||||
`maven-war-plugin` 设置了 `failOnMissingWebXml=false`,即使删掉它也能打包。
|
||||
|
||||
**DispatcherServlet 只映射 `/api/*`**:`/api` 前缀外的请求仍由 Tomcat 默认 Servlet 处理(404 或欢迎页),
|
||||
避免传统 war 里 DispatcherServlet 抢占 `/` 后静态资源失效。`web.xml` 式项目可以同样用 `<url-pattern>/api/*</url-pattern>`。
|
||||
|
||||
**context.xml**:`src/main/webapp/META-INF/context.xml` 只是占位文件,用来把该目录纳入构建上下文;
|
||||
它不参与启动流程,删掉不影响运行。
|
||||
|
||||
**上下文路径**:war 文件名即上下文路径,`finalName` 固定为 `spring-war17`,所以是 `/spring-war17`。
|
||||
想让应用直接挂在根路径 `/`,把 war 改名为 `ROOT.war` 即可。
|
||||
|
||||
**两阶段构建**:build 阶段在 `compile-maven3-jdk17` 里 `mvn package`,runtime 阶段只把 war 拷进官方 Tomcat 镜像,
|
||||
运行镜像不含 Maven/源码。Tomcat 镜像保留官方默认布局,只清空自带 `webapps/*`。
|
||||
|
||||
**端口**:容器内 Tomcat 仍是 8080(官方镜像默认),宿主机映射到 8085。
|
||||
|
||||
**JSON 输出**:`@EnableWebMvc` 只会注册 Spring 自带的转换器(ByteArray/String/Resource 及 JAXB 等),
|
||||
非 Boot 项目里 **Jackson 不会自动带入**。所以 `pom.xml` 显式声明了 `jackson-databind`,
|
||||
Spring 检测到它会自动注册 `MappingJackson2HttpMessageConverter`,`/api/*` 返回 `Map` 即得 JSON;
|
||||
缺了它就会像最常见的排查题那样返回 `HTTP 406 Not Acceptable`(Tomcat 自己的错误页,`Acceptable representations: []`)。
|
||||
|
||||
**健康检查**:compose 用 `curl` 探测 `/spring-war17/api/info`,`start_period: 30s` 覆盖 war 解压与 Spring 初始化;
|
||||
`runtime-tomcat10` 已装 `curl`,无需额外安装。
|
||||
|
||||
### 运维命令
|
||||
|
||||
```shell
|
||||
docker logs -f spring-war17-demo # catalina.out 日志
|
||||
docker exec spring-war17-demo ls /usr/local/tomcat/webapps # 查看已部署应用(war 与解包目录)
|
||||
docker exec spring-war17-demo java -version # 确认 JDK 版本
|
||||
```
|
||||
|
||||
### 调试时直接在编译镜像里跑
|
||||
|
||||
```shell
|
||||
docker run --rm -it -v "$PWD":/src -w /src \
|
||||
registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-maven3-jdk17 \
|
||||
mvn -B clean package
|
||||
```
|
||||
|
||||
得到的 `target/spring-war17.war` 可以拷到任意 Tomcat 10.1 的 `webapps/` 下部署。
|
||||
|
||||
### 停止
|
||||
|
||||
```shell
|
||||
sh shutdown.sh
|
||||
```
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-spring-war17}
|
||||
docker build -t "${IMAGE}" .
|
||||
|
||||
if [ "${PUSH:-0}" = "1" ]; then
|
||||
docker push "${IMAGE}"
|
||||
fi
|
||||
@@ -0,0 +1,30 @@
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
spring-war17-demo:
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: "172.30.2.0/24"
|
||||
|
||||
services:
|
||||
demo:
|
||||
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-spring-war17 # 镜像由 build.sh 构建
|
||||
container_name: spring-war17-demo
|
||||
restart: unless-stopped
|
||||
ports: # 映射端口:8085 -> 容器内 Tomcat 8080
|
||||
- "8085:8080"
|
||||
environment: # 设置环境变量,相当于docker run命令中的-e
|
||||
TZ: Asia/Shanghai
|
||||
JAVA_OPTS: "-Xms128m -Xmx256m -Duser.timezone=Asia/Shanghai"
|
||||
CATALINA_OPTS: "-Djava.security.egd=file:/dev/./urandom"
|
||||
healthcheck:
|
||||
# runtime-tomcat10 已装 curl,直接探测健康页面;start_period 覆盖 war 解压与 Spring 初始化
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/spring-war17/api/info > /dev/null"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
networks:
|
||||
spring-war17-demo:
|
||||
ipv4_address: 172.30.2.20
|
||||
@@ -0,0 +1,76 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>cn.odboy</groupId>
|
||||
<artifactId>spring-war17</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<!-- war 包,部署到外置 Tomcat 10.1;不用 Boot 父 POM,版本全部显式声明 -->
|
||||
<packaging>war</packaging>
|
||||
<name>spring-war17</name>
|
||||
<description>Spring MVC 6 + 外置 Tomcat 10.1 的 war 包示例</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.release>${java.version}</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<spring.version>6.2.1</spring.version>
|
||||
<thymeleaf-spring6.version>3.1.2.RELEASE</thymeleaf-spring6.version>
|
||||
<jackson.version>2.18.2</jackson.version>
|
||||
<jakarta.servlet-api.version>6.0.0</jakarta.servlet-api.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- spring-webmvc 已传递 spring-core/beans/context/web/aop/expression -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring6</artifactId>
|
||||
<version>${thymeleaf-spring6.version}</version>
|
||||
</dependency>
|
||||
<!-- JSON 序列化:非 Boot 项目不会自动带入 Jackson,@RestController 返回 Map 必须显式声明 -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- JSP/Servlet API 由 Tomcat 提供,编译期需要,不打进 war -->
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>${jakarta.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- spring-war17.war,部署后上下文路径即 /spring-war17(也可改名) -->
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>${java.version}</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- 去掉版本号,war 文件名与 upstream/ 部署名一致 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p spring-war17-demo down
|
||||
@@ -0,0 +1,75 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.servlet.ServletContext;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.SpringVersion;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 运行时信息接口。与 demo/app-simple/springboot-jar17 里的同名类保持一致的输出结构,方便对比 jar 与 war 两种打包方式。
|
||||
*/
|
||||
@RestController
|
||||
public class DemoController {
|
||||
|
||||
private static final ZoneId TZ8 = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
|
||||
|
||||
@Autowired(required = false)
|
||||
private ServletContext servletContext;
|
||||
|
||||
@GetMapping({"/", "/info"})
|
||||
public Map<String, Object> info() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("message", "spring-war17 is running");
|
||||
body.put("java", System.getProperty("java.version"));
|
||||
body.put("javaHome", System.getProperty("java.home"));
|
||||
body.put("vm", System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version"));
|
||||
body.put("spring", SpringVersion.getVersion());
|
||||
body.put("application", "Spring MVC " + SpringVersion.getVersion() + " + " + servletContextName());
|
||||
body.put("os", System.getProperty("os.name") + " " + System.getProperty("os.arch"));
|
||||
body.put("hostname", hostname());
|
||||
body.put("contextPath", servletContext == null ? "" : servletContext.getContextPath());
|
||||
body.put("zoneId", ZoneId.systemDefault().getId());
|
||||
body.put("time", ZonedDateTime.now(TZ8).format(TIME_FMT));
|
||||
body.put("uptime", Duration.ofMillis(uptimeMillis).toString());
|
||||
body.put("memory", runtime.totalMemory() / 1024 / 1024 + "MB / max " + runtime.maxMemory() / 1024 / 1024 + "MB");
|
||||
return body;
|
||||
}
|
||||
|
||||
@GetMapping("/hello/{name}")
|
||||
public Map<String, Object> hello(@PathVariable String name) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("message", "Hello, " + name + "!");
|
||||
body.put("time", ZonedDateTime.now(TZ8).format(TIME_FMT));
|
||||
return body;
|
||||
}
|
||||
|
||||
private String servletContextName() {
|
||||
if (servletContext == null) {
|
||||
return "Tomcat";
|
||||
}
|
||||
return servletContext.getServerInfo();
|
||||
}
|
||||
|
||||
private static String hostname() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception e) {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* 页面路由,模板见 src/main/resources/templates/index.html。
|
||||
*/
|
||||
@Controller
|
||||
public class PageController {
|
||||
|
||||
private final DemoController demoController;
|
||||
|
||||
public PageController(DemoController demoController) {
|
||||
this.demoController = demoController;
|
||||
}
|
||||
|
||||
/** 渲染 templates/index.html;/api/page 返回页面,其它 /api/* 仍返回 JSON */
|
||||
@GetMapping("/page")
|
||||
public String page(Model model) {
|
||||
Map<String, Object> info = demoController.info();
|
||||
model.addAttribute("info", info);
|
||||
return "index";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
/**
|
||||
* 替代 web.xml:Tomcat 10.1 启动时通过 Servlet 3+ 的 ServiceLoader 发现本类,
|
||||
* 由它注册 DispatcherServlet 与根容器。前缀 /api 的请求进 Spring MVC,其余请求交给 Tomcat 默认 Servlet。
|
||||
*/
|
||||
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class<?>[]{WebConfig.class};
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[]{"/api/*"};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
|
||||
/**
|
||||
* Spring MVC 配置。@EnableWebMvc 已注册包括 Jackson JSON 在内的默认消息转换器,
|
||||
* 这里只额外加上 Thymeleaf 视图解析。
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan("cn.odboy.demo")
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureViewResolvers(ViewResolverRegistry registry) {
|
||||
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
|
||||
// 与 springboot-jar17 保持同一套模板路径:src/main/resources/templates/*.html
|
||||
resolver.setPrefix("templates/");
|
||||
resolver.setSuffix(".html");
|
||||
resolver.setTemplateMode("HTML");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setCacheable(true);
|
||||
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.setTemplateResolver(resolver);
|
||||
|
||||
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
|
||||
viewResolver.setTemplateEngine(engine);
|
||||
viewResolver.setCharacterEncoding("UTF-8");
|
||||
viewResolver.setOrder(1);
|
||||
registry.viewResolver(viewResolver);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>spring-war17 运行信息</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; margin: 40px; color: #222; }
|
||||
h1 { font-size: 20px; }
|
||||
table { border-collapse: collapse; min-width: 520px; }
|
||||
th, td { border: 1px solid #ddd; padding: 6px 12px; text-align: left; }
|
||||
th { background: #f5f5f5; width: 160px; }
|
||||
code { background: #f5f5f5; padding: 1px 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>spring-war17 运行信息</h1>
|
||||
<table>
|
||||
<tr th:each="entry : ${info}">
|
||||
<th th:text="${entry.key}">key</th>
|
||||
<td th:text="${entry.value}">value</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>
|
||||
其他接口:<code>api/info</code>、<code>api/hello/{name}</code>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Tomcat 部署描述符,不影响 Spring 初始化。当前版本没有用 web.xml 写 servlet 映射,
|
||||
由 WebAppInitializer(ServletContainerInitializer)注册 DispatcherServlet。
|
||||
要改会话超时或 MIME 类型时才需要改这里。
|
||||
-->
|
||||
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
|
||||
version="6.0"
|
||||
metadata-complete="false">
|
||||
|
||||
<display-name>spring-war17</display-name>
|
||||
|
||||
<session-config>
|
||||
<session-timeout>30</session-timeout>
|
||||
</session-config>
|
||||
|
||||
</web-app>
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p spring-war17-demo up -d
|
||||
@@ -0,0 +1,4 @@
|
||||
target/
|
||||
src/main/webapp/
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,3 @@
|
||||
target/
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -0,0 +1,22 @@
|
||||
# 编译阶段:compile-maven3-jdk17(JDK 17 + Maven 3.9.9 + 阿里云 Maven 源)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-maven3-jdk17 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# 先只拷贝 POM 预热依赖层:源码改动不会让依赖缓存失效
|
||||
COPY pom.xml ./
|
||||
RUN mvn -B -q dependency:go-offline
|
||||
|
||||
COPY src ./src
|
||||
RUN mvn -B -q clean package -DskipTests \
|
||||
&& cp target/springboot-jar17.jar /src/app.jar
|
||||
|
||||
# 运行阶段:runtime-jdk17(仅 JDK,不含 Maven)
|
||||
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-jdk17 AS runtime
|
||||
LABEL MAINTAINER="tianjun@odboy.cn"
|
||||
ENV TimeZone=Asia/Shanghai
|
||||
ENV APP_PORT=8084
|
||||
WORKDIR /home/admin
|
||||
COPY --from=build /src/app.jar ./
|
||||
EXPOSE 8084
|
||||
# exec 形式,保证 docker stop 的 SIGTERM 能被 JVM 收到,触发 Spring 优雅停机
|
||||
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-Duser.timezone=Asia/Shanghai", "-jar", "/home/admin/app.jar"]
|
||||
@@ -0,0 +1,90 @@
|
||||
# springboot-jar17 示例
|
||||
|
||||
演示如何用 `compile-maven3-jdk17` + `runtime-jdk17` 两阶段构建并运行一个 Spring Boot 3 Web 应用,产物是**可执行 jar**(内嵌 Tomcat)。
|
||||
|
||||
| 阶段 | 镜像 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-maven3-jdk17` | JDK 17 + Maven 3.9.9 + 阿里云 Maven 源(见 `image/compile-maven3-jdk17`) |
|
||||
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-jdk17` | 仅 JDK 17(见 `image/runtime-jdk17`) |
|
||||
|
||||
运行阶段只拷贝 `spring-boot-maven-plugin` 重打包后的 jar,镜像里不含 Maven、源码和 `~/.m2`。
|
||||
|
||||
### 示例内容
|
||||
|
||||
```
|
||||
springboot-jar17/
|
||||
├── pom.xml # Spring Boot 3.4.1,Java 17,parent 统一管版本
|
||||
├── src/main/java/cn/odboy/demo/
|
||||
│ ├── DemoApplication.java # @SpringBootApplication 入口
|
||||
│ ├── DemoController.java # @RestController:/ 、/api/info、/api/hello/{name}
|
||||
│ └── PageController.java # @Controller:/page 渲染 Thymeleaf 模板
|
||||
├── src/main/resources/
|
||||
│ ├── application.yml # 端口 8084、优雅停机、actuator 只开 health
|
||||
│ └── templates/index.html # /page 页面
|
||||
├── Dockerfile # 两阶段:compile-maven3-jdk17 -> runtime-jdk17
|
||||
├── build.sh # 构建镜像(PUSH=1 时同时推送)
|
||||
├── docker-compose.yml # 部署编排(端口 8084,固定 IP 172.30.1.20)
|
||||
├── startup.sh # docker-compose up -d
|
||||
└── shutdown.sh # docker-compose down
|
||||
```
|
||||
|
||||
### 构建与部署
|
||||
|
||||
```shell
|
||||
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-springboot-jar17 .
|
||||
PUSH=1 sh build.sh # 构建并推送
|
||||
sh startup.sh # docker-compose -f docker-compose.yml -p springboot-jar17-demo up -d
|
||||
```
|
||||
|
||||
访问:
|
||||
|
||||
```shell
|
||||
curl http://127.0.0.1:8084/ # {"message":"springboot-jar17 is running","java":"17.0.x",...}
|
||||
curl http://127.0.0.1:8084/api/info # 同上,等价入口
|
||||
curl http://127.0.0.1:8084/api/hello/demo # {"message":"Hello, demo!","time":"..."}
|
||||
curl http://127.0.0.1:8084/actuator/health # {"status":"UP"}
|
||||
```
|
||||
|
||||
浏览器打开 http://127.0.0.1:8084/page 可看到渲染后的运行信息页面。
|
||||
|
||||
### 关键点
|
||||
|
||||
**依赖层缓存**:先只 `COPY pom.xml` 执行 `mvn dependency:go-offline`,再 `COPY src` 编译。只改源码时不会重新下载依赖;
|
||||
镜像源已在 `compile-maven3-jdk17` 的 `settings.xml` 里指向阿里云,无需额外换源。
|
||||
|
||||
**两阶段构建**:Maven 仓库、编译中间产物都留在 build 阶段,最终镜像只多一个 jar。这也是 `runtime-jdk*` 与 `compile-maven3-*` 分开的原因。
|
||||
|
||||
**监听地址**:容器内 8084(`server.port=${APP_PORT:8084}`),避开 dotnet6/8/9(8080-8082)、python310-flask(8083)、spring-war17(8085)。
|
||||
|
||||
**时区**:启动参数带 `-Duser.timezone=Asia/Shanghai`,compose 再声明 `TZ`;接口里额外按 UTC+8 输出时间,双保险。
|
||||
|
||||
**优雅停机**:`server.shutdown=graceful`,`ENTRYPOINT` 用 exec 形式,`docker stop` 的 SIGTERM 直接到 JVM。
|
||||
|
||||
**内存**:`-XX:MaxRAMPercentage=75.0` 让 JVM 按容器内存上限算堆;compose 里用 `JAVA_OPTS` 演示另一种覆盖方式(需自行在 Dockerfile 里接 `JAVA_OPTS`,本示例入口为固定数组)。
|
||||
|
||||
### 运维命令
|
||||
|
||||
```shell
|
||||
docker logs -f springboot-jar17-demo # 应用日志
|
||||
docker exec springboot-jar17-demo java -version # 确认 JDK 版本
|
||||
docker exec springboot-jar17-demo sh -c 'ls -lh /home/admin'
|
||||
```
|
||||
|
||||
### 调试时直接在编译镜像里运行
|
||||
|
||||
需要看编译报错或临时跑一下时,可以只挂载源码进编译镜像(Maven 依赖缓存在容器内 `~/.m2`):
|
||||
|
||||
```shell
|
||||
docker run --rm -it -p 8084:8084 -v "$PWD":/src -w /src \
|
||||
registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-maven3-jdk17 \
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
想把宿主机的 `~/.m2` 复用到构建里,也可以给 `build.sh` 的 `docker build` 加
|
||||
`--build-arg`/`--mount=type=cache,target=/root/.m2` 之类的 BuildKit 缓存(本示例为简单起见未启用)。
|
||||
|
||||
### 停止
|
||||
|
||||
```shell
|
||||
sh shutdown.sh
|
||||
```
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-springboot-jar17}
|
||||
docker build -t "${IMAGE}" .
|
||||
|
||||
if [ "${PUSH:-0}" = "1" ]; then
|
||||
docker push "${IMAGE}"
|
||||
fi
|
||||
@@ -0,0 +1,30 @@
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
springboot-jar17-demo:
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: "172.30.1.0/24"
|
||||
|
||||
services:
|
||||
demo:
|
||||
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-springboot-jar17 # 镜像由 build.sh 构建
|
||||
container_name: springboot-jar17-demo
|
||||
restart: unless-stopped
|
||||
ports: # 映射端口
|
||||
- "8084:8084"
|
||||
environment: # 设置环境变量,相当于docker run命令中的-e
|
||||
TZ: Asia/Shanghai
|
||||
APP_PORT: "8084"
|
||||
JAVA_OPTS: "-Xms128m -Xmx256m"
|
||||
healthcheck:
|
||||
# 运行镜像自带 net-tools,直接用端口探测,不额外安装 curl
|
||||
test: ["CMD-SHELL", "netstat -tln | grep -q ':8084 '"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
networks:
|
||||
springboot-jar17-demo:
|
||||
ipv4_address: 172.30.1.20
|
||||
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!-- 父 POM 锁 Spring Boot 3.4.1;3.x 要求 JDK 17+,与 compile-maven3-jdk17 对应 -->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.4.1</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>cn.odboy</groupId>
|
||||
<artifactId>springboot-jar17</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>springboot-jar17</name>
|
||||
<description>Spring Boot 3 + 内嵌 Tomcat,打成可执行 jar</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- Web MVC + Jackson + 内嵌 Tomcat(jar 包,可直接 java -jar 启动) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<!-- repackage 生成 BOOT-INF 结构的可执行 jar,Main-Class 为 JarLauncher -->
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p springboot-jar17-demo down
|
||||
@@ -0,0 +1,12 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.SpringVersion;
|
||||
import org.springframework.boot.SpringBootVersion;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 运行时信息接口,用于确认镜像里的 JDK / 时区 / 端口等是否符合预期。
|
||||
*/
|
||||
@RestController
|
||||
public class DemoController {
|
||||
|
||||
private static final ZoneId TZ8 = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
|
||||
|
||||
@Value("${app.name:spring demo}")
|
||||
private String appName;
|
||||
|
||||
@Value("${server.port:0}")
|
||||
private int port;
|
||||
|
||||
/** 返回 JDK、Spring 版本、主机名、时区与运行时长,浏览器可直接看 JSON */
|
||||
@GetMapping({"/", "/api/info"})
|
||||
public Map<String, Object> info() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("message", appName + " is running");
|
||||
body.put("java", System.getProperty("java.version"));
|
||||
body.put("javaHome", System.getProperty("java.home"));
|
||||
body.put("vm", System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version"));
|
||||
body.put("spring", SpringVersion.getVersion());
|
||||
body.put("application", "Spring Boot " + SpringBootVersion.getVersion());
|
||||
body.put("os", System.getProperty("os.name") + " " + System.getProperty("os.arch"));
|
||||
body.put("hostname", hostname());
|
||||
body.put("port", port);
|
||||
body.put("zoneId", ZoneId.systemDefault().getId());
|
||||
body.put("time", ZonedDateTime.now(TZ8).format(TIME_FMT));
|
||||
body.put("uptime", Duration.ofMillis(uptimeMillis).toString());
|
||||
body.put("memory", runtime.totalMemory() / 1024 / 1024 + "MB / max " + runtime.maxMemory() / 1024 / 1024 + "MB");
|
||||
return body;
|
||||
}
|
||||
|
||||
/** 带路径参数的示例接口 */
|
||||
@GetMapping("/api/hello/{name}")
|
||||
public Map<String, Object> hello(@PathVariable String name) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("message", "Hello, " + name + "!");
|
||||
body.put("time", ZonedDateTime.now(TZ8).format(TIME_FMT));
|
||||
return body;
|
||||
}
|
||||
|
||||
private static String hostname() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception e) {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.odboy.demo;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* 页面路由,模板见 src/main/resources/templates/index.html。
|
||||
*/
|
||||
@Controller
|
||||
public class PageController {
|
||||
|
||||
private final DemoController demoController;
|
||||
|
||||
public PageController(DemoController demoController) {
|
||||
this.demoController = demoController;
|
||||
}
|
||||
|
||||
/** 渲染 templates/index.html;只有 /page 返回页面,接口仍返回 JSON */
|
||||
@GetMapping("/page")
|
||||
public String page(Model model) {
|
||||
Map<String, Object> info = demoController.info();
|
||||
model.addAttribute("info", info);
|
||||
return "index";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
server:
|
||||
port: ${APP_PORT:8084}
|
||||
shutdown: graceful
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: springboot-jar17
|
||||
lifecycle:
|
||||
timeout-per-shutdown-phase: 20s
|
||||
|
||||
app:
|
||||
name: springboot-jar17
|
||||
|
||||
# 健康检查只需要端口探测,actuator 只暴露 health
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health
|
||||
endpoint:
|
||||
health:
|
||||
show-details: never
|
||||
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
@@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>springboot-jar17 运行信息</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; margin: 40px; color: #222; }
|
||||
h1 { font-size: 20px; }
|
||||
table { border-collapse: collapse; min-width: 520px; }
|
||||
th, td { border: 1px solid #ddd; padding: 6px 12px; text-align: left; }
|
||||
th { background: #f5f5f5; width: 160px; }
|
||||
code { background: #f5f5f5; padding: 1px 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>springboot-jar17 运行信息</h1>
|
||||
<table>
|
||||
<tr th:each="entry : ${info}">
|
||||
<th th:text="${entry.key}">key</th>
|
||||
<td th:text="${entry.value}">value</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>
|
||||
其他接口:<code>/api/info</code>、<code>/api/hello/{name}</code>、<code>/actuator/health</code>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p springboot-jar17-demo up -d
|
||||
Reference in New Issue
Block a user