dockerdocker-composedockerfilehost

Add Entryes to Host File in Windows and Ubuntu from Docker Deployment


Is it possible from Docker to modify (Add) to the host file of the HOST operating system: Windows or its equivalent in Ubuntu and create the URL and IP address entries?

I hope to be able to add dynamically in the process of executing the command:

docker-compose up -d

Note:

127.0.0.1 www.lh-2.dock lh-2.dock
127.0.0.1 www.lh-2.pma.dock lh-2.pma.dock

Try:

version: '3'
services:
  myapp:
    image: image_app
    container_name: container_app
    volumes:
      - E:\Web\LH2\docker\hosts:C:\Windows\System32\drivers\etc\hosts
    command: cmd /c "echo 127.0.0.1 www.lh-2.dock lh-2.dock >> C:\Windows\System32\drivers\etc\hosts && echo 127.0.0.1 www.lh-2.pma.dock lh-2.pma.dock >> C:\Windows\System32\drivers\etc\hosts && your_start_command"

and

version: '3'
services:
  myapp:
    image: image_app
    container_name: container_app
    volumes:
      - /media/developer1/device/Web/LH2/docker/hosts:/etc/hosts
    command: sh -c "echo '127.0.0.1 www.lh-2.dock lh-2.dock' >> /etc/hosts && echo '127.0.0.1 www.lh-2.pma.dock lh-2.pma.dock' >> /etc/hosts && tu_comando_de_inicio"

How can I merge the two environments that were deployed on Windows/Linux and let the system select the appropriate environment?


Solution

  • The only way to do it that I can think of is through a script in the host operating system, although the approach changes a little, the idea of docker and containers is not to affect the host operating system, for this reason it is important to consider scripting.

    In case someone gets here, the way to solve it with a Windows operating system as a host is to create a .ps1 file:

    $main_url = "lh-2.dock"
    $pma_url = "pma.lh-2.dock"
    $hosts_file = "${env:SystemRoot}\System32\drivers\etc\hosts"
    $host_entry = "127.0.0.1 $main_url  $pma_url"
    $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")
        $current_content = $current_content -replace "(\r?\n)+\z", ""
        Set-Content -Path $hosts_file -Value $current_content
        Write-Host " --> Updated operating system hosts file."
    } else {
        $current_content += "`n`n# Developer Area Docker`n$host_entry`n# End of section"
        $current_content = $current_content -replace "(\r?\n)+\z", ""
        Set-Content -Path $hosts_file -Value $current_content
        Write-Host " --> The Host section was added at the end of the hosts file."
    }
    $path = Join-Path -Path $scriptDirectory -ChildPath "docker-compose.yaml"
    docker-compose -f $path up -d --force-recreate
    

    If anyone knows how to do it in Linux and macOS, they would be welcome to give their answer.