<# 用法:在 PowerShell 中执行本脚本,自动构建并重启 AdminApi 容器。 如果要放到桌面双击运行,可将本文件复制到桌面后右键“使用 PowerShell 运行”。 前置:已安装并运行 Docker Desktop。 #> # 遇到异常时停住窗口,方便查看错误 trap { Write-Host "发生错误:" $_ -ForegroundColor Red Read-Host "按回车关闭窗口" exit 1 } $ErrorActionPreference = 'Stop' # 1. 基本变量(脚本位于 repo_root/scripts,下移一层再上跳到仓库根) $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path $repoRoot = Split-Path -Parent $scriptDir $imageName = if ($env:IMAGE_NAME) { $env:IMAGE_NAME } else { 'takeout.api.admin:dev' } $containerName = if ($env:CONTAINER_NAME) { $env:CONTAINER_NAME } else { 'takeout.api.admin' } $buildConfiguration = if ($env:BUILD_CONFIGURATION) { $env:BUILD_CONFIGURATION } else { 'Release' } $dockerNetwork = if ($env:DOCKER_NETWORK) { $env:DOCKER_NETWORK } else { 'web_apps' } $dockerfilePath = Join-Path $repoRoot 'src/Api/TakeoutSaaS.AdminApi/Dockerfile' Write-Host "工作目录:$repoRoot" # 2. 先构建镜像(减少停机时间;同时避免每次都删除镜像导致缓存失效) Write-Host "开始构建镜像:$imageName (Configuration=$buildConfiguration)" docker build -f $dockerfilePath -t $imageName --build-arg "BUILD_CONFIGURATION=$buildConfiguration" $repoRoot # 3. 停止并删除旧容器 if ((docker ps -a --format '{{.Names}}') -contains $containerName) { Write-Host "发现旧容器,正在移除:$containerName" docker rm -f $containerName | Out-Null } # 4. 运行新容器并映射端口 $runArgs = @() if (-not [string]::IsNullOrWhiteSpace($dockerNetwork)) { $networkExists = (docker network ls --format '{{.Name}}') -contains $dockerNetwork if (-not $networkExists) { Write-Host "Docker network 不存在,正在创建:$dockerNetwork" docker network create $dockerNetwork | Out-Null } $runArgs += @('--network', $dockerNetwork) } Write-Host "运行新容器:$containerName (端口映射 7801:7801,环境 Development,网络 $dockerNetwork)" docker run -d --name $containerName @runArgs -e ASPNETCORE_ENVIRONMENT=Development -p 7801:7801 $imageName Write-Host "完成。镜像:$imageName,容器:$containerName。Swagger 访问:http://localhost:7801/swagger"