Skip to content

Instantly share code, notes, and snippets.

@mtfelian
Last active January 10, 2023 15:58
Show Gist options
  • Save mtfelian/74e246300ace9a630099be9c4e134b06 to your computer and use it in GitHub Desktop.
Save mtfelian/74e246300ace9a630099be9c4e134b06 to your computer and use it in GitHub Desktop.
PS script to recreate DB Postgis container on Windows Docker Desktop, wait for DB init completes and create databases
docker ps -q | % { docker stop $_ }
docker container prune -f
$containerName = "postgis"
docker run -d --name $containerName -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres postgis/postgis:13-3.2
$maxWaitTime = 15000 # milliseconds
$checkInterval = 500
$startTime = Get-Date
$dbnames = @(
"wis_dataspace_tests",
"dcc5_geobjects",
"wis_dataserver_tests",
"dcc_executors",
"dcc_buckets"
)
# by Health don't works, no such field in docker answer
# $containerStatus = (docker inspect --format='{{json .State}}' $containerName) | ConvertFrom-Json
# if ($containerStatus.Health.Status -eq "healthy") {
# Write-Host "Container $containerName is in a healthy state."
# break
# }
while ($true) {
try {
$pgIsReadyResult = docker exec $containerName pg_isready -U postgres
} catch {
$elapsedTime = (Get-Date) - $startTime
if ($elapsedTime.TotalMilliseconds -gt $maxWaitTime) {
Write-Host "Timeout reached while waiting for container $containerName to be ready."
break
}
Start-Sleep -Milliseconds $checkInterval
continue
}
if ($pgIsReadyResult -match "accepting connections") {
Write-Host "Container $containerName is ready."
break
}
Start-Sleep -Milliseconds $checkInterval
}
Write-Host "Creating databases..."
foreach ($dbname in $dbnames) {
Write-Host " > $dbname"
docker exec -it $containerName psql --user=postgres --dbname=postgres -c "CREATE database $dbname"
}
Write-Host "Finished"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment