After a day of research, I did not find a software, extension or API that solved my problem so I had to resort to scripting in the OS so I would consider that this question was solved more as a super user or programmer than with a recommended software; Even so, I do not consider this to be a definitive answer, so I consider that it can be improved with time and the contribution of other users.
To achieve the goal it was necessary to make some changes to the structure, we started with changes to the .env
file:
LH_URL="lh-2"
LH_URL_HOST="127.0.0.1 ${LH_URL}.dock ${LH_URL}.pma.dock ${LH_URL}.revprox.dock"
then implement a very basic test .yml file, :
version: '3'
services:
web:
image: nginx
container_name: ReverseProxy
ports:
- "80:80"
networks:
default:
aliases:
- lh-2.revprox.dock
volumes:
- ./reverse-proxy.conf:/etc/nginx/conf.d/reverse-proxy.conf
command: [ nginx, '-g', 'daemon off;' ]
note: I am not interested in validating this part if it works since it was not the initial objective, this can be replaced by any yml file that works correctly
Finally, what really does the magic is a script for PowerShell:
# Feature to check if you are running as administrator
function Get-Administrator {
$isAdministrator = (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdministrator) {
$scriptPath = $MyInvocation.MyCommand.ScriptBlock.File
Start-Process -FilePath 'powershell' -ArgumentList ('-File', $scriptPath) -Verb RunAs
exit
}
}
function Get-Pause {
Read-Host "`n Press Enter to continue..."
}
function Set-EnvironmentVariables {
$envFilePath = Join-Path -Path $scriptDirectory -ChildPath ".env"
if (Test-Path $envFilePath) {
Write-Host "`n Found the .env file in the following location: $((Get-Item -Path $envFilePath).FullName)"
$envFileContent = Get-Content $envFilePath -Raw
$envVariablesRaw = @{}
$lineOrder = 0 # Inicializar el contador de orden
$envFileContent -split [Environment]::NewLine | ForEach-Object {
$line = $_.Trim()
if ($line -match '^([^#=]+)=(.*)$') {
$Key = $Matches[1]
$Value = $Matches[2]
$envVariablesRaw[$Key] = @{
'Value' = $Value
'Order' = $lineOrder # Registrar el orden original
}
$lineOrder++
}
}
$sortedEnvVariables = $envVariablesRaw.GetEnumerator() | Sort-Object { $_.Value.Order }
$sortedEnvVariables | ForEach-Object {
$var_name = $_.Key
$var_value = $_.Value.Value
$expresionRegular = '\$\{([^}]*)\}'
$coincidencias = [System.Text.RegularExpressions.Regex]::Matches($var_value, $expresionRegular)
foreach ($coincidencia in $coincidencias) {
$textoEncontrado = $coincidencia.Groups[1].Value
$env_value = [System.Environment]::GetEnvironmentVariable("INSTALL_$textoEncontrado")
if (![string]::IsNullOrEmpty($env_value)) {
$var_value = $var_value.Replace($coincidencia, $env_value)
}
$var_value = $var_value -replace '"', ''
}
[System.Environment]::SetEnvironmentVariable("INSTALL_$var_name", $var_value, [System.EnvironmentVariableTarget]::Process)
}
if ([System.Environment]::GetEnvironmentVariable("INSTALL_LH_SYSTEM_NAME") -and [System.Environment]::GetEnvironmentVariable("INSTALL_LH_URL_HOST")) {
return $true
} else {
Write-Host " LH_SYSTEM_NAME/LH_URL_HOST environment variables are not defined in the .env file"
Get-Pause
exit
}
} else {
Write-Host " Environment Variables File not found."
Get-Pause
exit
}
}
function Initialize-Docker {
Write-Host "`n The docker service is being validated..."
$dockerIsRunning = (docker ps 2>&1) -match '^(?!error)'
if ($dockerIsRunning){
Write-Host " The Docker Desktop and Service is running."
Get-Pause
} else {
Write-Host " You must install and open Docker Desktop before using this program."
Get-Pause
exit
}
[Console]::Clear()
Write-Host "`n Starting the downloading of image and construction of containers..."
$env:DOCKER_HOST = "tcp://localhost:2375"
docker-compose -f docker-compose.yml up -d --force-recreate
Get-Pause
}
function Set-IpAddress {
[Console]::Clear()
$lh_url = [System.Environment]::GetEnvironmentVariable("INSTALL_LH_SYSTEM_NAME")
$lh_url_host = [System.Environment]::GetEnvironmentVariable("INSTALL_LH_URL_HOST")
$resolved_url_host = $ExecutionContext.InvokeCommand.ExpandString($lh_url_host)
$resolved_url_host = $resolved_url_host -replace '"', ''
$urls = $resolved_url_host -split ' '
$web_server = $urls[0];
$phpmyadmin = $urls[1];
$proxy_container = "Proxy-Server"
$ip_address = (docker inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" $proxy_container)
$ip_pattern = "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"
if ($ip_address -match $ip_pattern) {
$hosts_file = "${env:SystemRoot}\System32\drivers\etc\hosts"
# you can implement ip container detection or set up 127.0.0.1
# $host_entry = "$ip_address $resolved_url_host"
$host_entry = "127.0.0.1 $resolved_url_host"
$current_content = Get-Content $hosts_file -Raw
$pattern = "(?ms)(# Developer Area Docker.*?# End of section)"
if ($current_content -match $pattern) {
$current_content = $current_content -replace $pattern, ("# Developer Area Docker`n$host_entry`n# End of section")
Set-Content -Path $hosts_file -Value $current_content
Write-Host "`n The URLs were successfully updated in the Host section!!!"
Get-Pause
} else {
$current_content += "`n`n# Developer Area Docker`n$host_entry`n# End of section"
Set-Content -Path $hosts_file -Value $current_content
Write-Host "`n The Host section was added at the end of the hosts file!!!"
Get-Pause
}
} else {
Write-Host "`n Could not get container IP address $containerName."
Get-Pause
exit
}
[Console]::Clear()
Write-Host "`n The installation of the development environment is complete."
Write-Host "`n You will have access to urls:"
Write-Host " web server with: http://$web_server/"
Write-Host " phpmyadmin with: http://$phpmyadmin/`n"
Get-Pause
}
Get-Administrator
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location -Path $scriptDirectory
$env_exit = Set-EnvironmentVariables
if($env_exit -eq $true){
Initialize-Docker
Set-IpAddress
}
This is my final version, with the implementation of the IP detection for the "ReverseProxy" container, this container will not undergo changes.
In the end I achieved the goal: saving the local URL entries of the Windows hosts file and at the same time validating and trying to run the build and configuration of the Docker environment.
If anyone is interested, you can add or update this entry with the script for MAC OS / Linux