Publi

Cómo actualizar /etc/hosts con todos los contenedores docker que hay en ejecución

Si tenemos varios contenedores docker arrancados en nuestro ordenador. Muchas veces, nos interesará conectar con servicios corriendo dentro de cada uno de ellos. Algunos estarán lanzados simplemente con docker, otros con docker-compose, cada uno trabajando en un sistema distinto, y necesitamos una forma más o menos sencilla de acceder a cada uno de ellos.

Con un pequeño script podemos recorrer todos los contenedores, pedir la dirección IP de cada uno de ellos y añadirlas al nuestro archivo /etc/hosts de forma que este archivo se actualice automáticamente cada vez que lanzamos el comando.

El script

Yo lo suelo llamar docker_update_hosts.sh, y suele estar en /usr/local/bin. En realidad, es un enlace el que está ahí:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash

function panic()
{
    echo "$@" >&2
    exit 1
}

if [ "`whoami`" != "root" ]
then
    panic "This program must be ran as root"
fi

# Clear /etc/hosts file
HEADER="# Added automatically by docker_update_hosts"
sed -i '/docker\.local$/d' /etc/hosts
sed -i "/$HEADER\$/d" /etc/hosts
# Remove empty lines at the end of file
sed -i  -e :a -e '/^\n*$/{$d;N;ba' -e '}' /etc/hosts

echo -e "\n$HEADER" >> /etc/hosts

IFS=$'\n' && ALLHOSTS=($( docker ps --format '{{.ID}} {{.Names}}'))

for line in ${ALLHOSTS[*]}; do
    IFS=" " read  -r ID NAME <<< "$line"
    IP="$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' $ID)"
    if [ -n "$IP" ]; then
        echo -e "$IP\t$NAME.docker.local" >> /etc/hosts
    fi
done

El script debe ser ejecutado como root, porque tiene que tener permiso para escribir en /etc/hosts. Para ello, en muchas distribuciones lo podremos ejecutar así:

sudo docker_update_hosts

Hosts

El script creará varios hosts llamados [contenedor].docker.local donde contenedor es el nombre de cada uno de nuestros contenedores. Al final, nos podremos juntar con algo como:

172.17.0.8 myphp5.6-fpm.docker.local
172.17.0.7 mongodb-testing.docker.local
172.17.0.6 wp-plugin-test.docker.local
172.17.0.5 myphp7.2-fpm.docker.local
172.17.0.4 mariadb-proyectos.docker.local
172.17.0.3 mariadb-testing.docker.local
172.17.0.2 redis.docker.local

De esta forma, podremos utilizar el nombre que le hemos dado en docker junto con «.docker.local» para referirnos al contenedor y llamar a un servicio encerrado en el mismo. Por ejemplo, para conectar con la base de datos mariadb-proyectos.docker.local podemos, desde el mismo ordenador host:

mysql -u root -p -h mariadb-proyectos.docker.local

Precauciones

Ya que el script está editando el archivo /etc/hosts y ese mismo fichero puede ser editable por nosotros, el script escribe un comentario:

1
# Added automatically by docker_update_hosts

Y debajo se escriben todos los hosts e IPs de contenedores docker que encontremos. Automáticamente, nada más ejecutar el script se busca el comentario y se buscan todos los hosts que terminen en .docker.local, por lo que si tenemos otras cosas que terminen en .docker.local serán eliminadas cuando se ejecute el script.

No tenemos que tener especial cuidado cuando editemos el fichero /etc/hosts manualmente. Podremos meter hosts nuevos al final, o encima de los hosts introducidos por el script y se respetarán.

Ejecutar automáticamente

Dependiendo de nuestra forma de trabajar, podemos ejecutar el script a mano siempre que sea necesario, ejecutarlo dentro de un script para lanzar contenedores o podemos ejecutarlo en un cron cada 10 minutos, por ejemplo.

Foto principal: unsplash-logoSherzod Max

También podría interesarte....

There are 49 comments left Ir a comentario

  1. Matias /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.14.1

    Excelente iniciativa! Hice un par de modificaciones porque el script no funcionaba en Mac OS

    #!/bin/bash

    function panic()
    {
    echo «$@» >&2
    exit 1
    }

    if [ «`whoami`» != «root» ]
    then
    panic «This program must be ran as root»
    fi

    # Clear /etc/hosts file
    HEADER=»# Added automatically by docker_update_hosts»
    sed -i » ‘/docker\.local$/d’ /etc/hosts
    sed -i » «/$HEADER\$/d» /etc/hosts
    # Remove empty lines at the end of file
    sed -i » -e :a -e ‘/^\n*$/{$d;N;ba’ -e ‘}’ /etc/hosts

    echo -e «\n$HEADER» >> /etc/hosts

    IFS=$’\n’ && ALLHOSTS=($( docker ps –format ‘{{.ID}} {{.Names}}’))

    for line in ${ALLHOSTS[*]}; do
    IFS=» » read -r ID NAME <<> /etc/hosts
    fi
    done

    1. Gaspar Fernández / Post Author
      Usando Mozilla Firefox Mozilla Firefox 64.0 en Ubuntu Linux Ubuntu Linux

      Hola Matías !
      Creo que falta un trozo de código al final. Por favor, pásamelo desde el formulario de contacto, github, o pastebin por favor.

      Gracias por tu comentario.

  2. Usando Google Chrome Google Chrome 72.0.3626.121 en Windows Windows NT

    Each of the proposed options will work in a different system, and we need a more or less easy way to access each of them.

  3. Anthony Scotte /
    Usando Google Chrome Google Chrome 106.0.0.0 en Windows Windows NT

    Very interesting information! Perfect just what I was searching for! Sunderland roofing

  4. Cleveland /
    Usando Google Chrome Google Chrome 106.0.0.0 en Windows Windows NT

    Your containers are now configured to update automatically whenever you publish a new Docker image to your image repository or when an external maintainer updates an image you’re following.

  5. Lesly Jacks /
    Usando Google Chrome Google Chrome 106.0.0.0 en Windows Windows NT

    I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for your usual wonderful effort. Check this out https://www.tejadosalcaladehenaresmadrid.com/

  6. my site /
    Usando Google Chrome Google Chrome 106.0.0.0 en Mac OS X Mac OS X 10.15.7

    This answered a lot of my questions, thank you. hire scaffolding Newcastle

  7. website /
    Usando Google Chrome Google Chrome 106.0.0.0 en Mac OS X Mac OS X 10.15.7

    This answered all of my questions, thanks. window installation Audenshaw

  8. Production companies near me /
    Usando Google Chrome Google Chrome 106.0.0.0 en Windows Windows NT

    I really enjoy reading and also appreciate your work. production company near me

  9. visit /
    Usando Google Chrome Google Chrome 106.0.0.0 en Mac OS X Mac OS X 10.15.7

    I appreciate the hard work that has gone into this. Aberdeen fencing

  10. here /
    Usando Google Chrome Google Chrome 106.0.0.0 en Mac OS X Mac OS X 10.15.7

    Answered all of my questions, thanks. Southend house rendering

  11. Website /
    Usando Google Chrome Google Chrome 106.0.0.0 en Mac OS X Mac OS X 10.15.7

    This is really helpful. Sheffield vehicle recovery

  12. Concrete contractor /
    Usando Google Chrome Google Chrome 106.0.0.0 en Windows Windows NT

    I also noticed that, Gaspar. a piece of code is missing at the end.

    Joey | concrete contractor

  13. moving service /
    Usando Google Chrome Google Chrome 107.0.0.0 en Windows Windows NT

    Thanks for the updates. Thank you for sharing.

  14. Leighton /
    Usando Google Chrome Google Chrome 107.0.0.0 en Windows Windows NT

    I am grateful for you all for sharing this. Thank you so much! 🙂
    social secuirty card Texas

  15. run 3 /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    It used to take me a long time to find my balance, but recently I discovered that a website sincerely guides this layout when you can find joy after a stressful day here.

  16. Anya /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    Thanks a lot very much for the high quality and results-oriented help. [url=https://www.google.com/]google[/url]
    google

  17. Brittany /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    I‘d mention that most of us visitors are endowed to exist in a fabulous place with very many wonderful individuals with very helpful things. Car Detailing Vancouver

  18. Website /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    Great post, thank you! ​​Scaffolding Tower Colchester

  19. bibou /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    I would like to say that I trully love to read each post you write. Please keep going and don’t listen to the people saying stop.
    Cass from ghmed

  20. Angel17 /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    Nice image. It was beautifully captured! 20 yard dumpster

  21. Cindy /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    Awesome blog! Thanks! Mobile scaffold tower Colchester

  22. Tara /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    Stunning blog. Thanks! Slate tilers in Doncaster

  23. Sydney /
    Usando Google Chrome Google Chrome 108.0.0.0 en Windows Windows NT

    demolition milton keynes

  24. Murphy /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Awesome blog. Silicone render in Essex

  25. sydrl /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Great tutorial! It is easy to understand and follow.

  26. our site /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    This is awesome.

  27. Marinan /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    I have always wondered about the importance of words, especially positive words that start with E since there are hundreds, if not thousands, of them.

  28. 카지노사이트추천 /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows 7

    The assignment submission period was over and I was nervous, 카지노사이트추천 and I am very happy to see your post just in time and it was a great help. Thank you ! Leave your blog address below. Please visit me anytime.

  29. stella jones /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Your blog and site can’t be praised as much because there is a lot of new stuff every time I visit, so I want to tell you a good and relaible wear for winter that is Bella Ramsey The Last of Us Blue Jacket is a best choice for style.

  30. benson /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Thanks for sharing this best stuff with us! Keep sharing! I am new in blog writing. All types of blogs and posts are not helpful for the readers. Here the author is giving good thoughts write my paper for me and suggestions to each and every reader through this article. literature-essay Quality of the content is the main element of the blog and this is the way of writing and presenting.

  31. Trichologist Manchester /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.15.7

    So helpful. Thank you very much

  32. Trichologist Manchester /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.15.7

    thanks so much

  33. Trichologist Manchester /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.15.7

    thanks

  34. Best Crypto Pump Groups Telegram /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.15.7

    Awesome thank you

  35. Davit Jack /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    I usually found very much informative squid game male green jumpsuit and interior usually found very much informative and interesting content on your blogs. I usually found very much informative and interesting content on your blogs. Keep posting more, thank you for sharing with us and giving us your special and precious time.

  36. Darmina /
    Usando Google Chrome Google Chrome 110.0.0.0 en Windows Windows NT

    Super informative content. Keep it up! Sandblasting

  37. Cleveland build closet /
    Usando Google Chrome Google Chrome 110.0.0.0 en Windows Windows NT

    This is a very useful piece of information for managing multiple containers and ensuring they can communicate with each other. Your contribution is greatly appreciated!

  38. FLAGLE /
    Usando Google Chrome Google Chrome 110.0.0.0 en Windows Windows NT

    Many thanks for keeping us informed. I am grateful that you shared this.

  39. 온라인카지노 /
    Usando Google Chrome Google Chrome 110.0.0.0 en Windows Windows NT

    While looking for articles on these topics, I came across this article on the site here. As I read your article, I felt like an expert in this field. I have several articles on these topics posted on my site. Could you please visit my homepage? 온라인카지노

  40. dordle luka /
    Usando Google Chrome Google Chrome 110.0.0.0 en Windows Windows NT

    The website contains a lot of valuable information. help me a lot. If you have more time, please visit: redactle

  41. 바카라사이트 /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    This is the perfect post.바카라사이트 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.

  42. star lord jacket /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    This is the first time that I visit here. I found so many exciting matters in this particular blog, One thing I would like to request is you that pls keep posting such type of informative blog star lord jacket

  43. Hayden /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    Great site! Cheers! car recovery near me

  44. Scalp Micropigmentation Manchester /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.15.7

    I like this site! I get a lot of information.

  45. Hair Systems Manchester /
    Usando Safari Safari 605.1.15 en Mac OS X Mac OS X 10.15.7

    Awesome site! Thanks!

  46. life the game /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    Hello, I sincerely hope that I can share with you one of the oldest games that has afforded me the opportunity to experience such a diverse range of emotions during the course of my life. You can rely on it completely. life the game

  47. Jacks /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    I am always searching for informative information like this. We from rehabilitacion fachada valladolid are looking forward to more updates from this site.

  48. 토토사이트순위 /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    Your ideas inspired me very much. 토토사이트순위 It’s amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you.

Leave a Reply