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.
Tabla de contenidos
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í:
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:
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: Sherzod Max
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
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.
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.
Very interesting information! Perfect just what I was searching for! Sunderland roofing
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.
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/
This answered a lot of my questions, thank you. hire scaffolding Newcastle
This answered all of my questions, thanks. window installation Audenshaw
I really enjoy reading and also appreciate your work. production company near me
I appreciate the hard work that has gone into this. Aberdeen fencing
Answered all of my questions, thanks. Southend house rendering
This is really helpful. Sheffield vehicle recovery
I also noticed that, Gaspar. a piece of code is missing at the end.
Joey | concrete contractor
Thanks for the updates. Thank you for sharing.
I am grateful for you all for sharing this. Thank you so much! 🙂
social secuirty card Texas
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.
Thanks a lot very much for the high quality and results-oriented help. [url=https://www.google.com/]google[/url]
google
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
Great post, thank you! Scaffolding Tower Colchester
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
Nice image. It was beautifully captured! 20 yard dumpster
Awesome blog! Thanks! Mobile scaffold tower Colchester
Stunning blog. Thanks! Slate tilers in Doncaster
demolition milton keynes
Awesome blog. Silicone render in Essex
Great tutorial! It is easy to understand and follow.
This is awesome.
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.
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.
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.
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.
So helpful. Thank you very much
thanks so much
thanks
Awesome thank you
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.
Super informative content. Keep it up! Sandblasting
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!
Many thanks for keeping us informed. I am grateful that you shared this.
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? 온라인카지노
The website contains a lot of valuable information. help me a lot. If you have more time, please visit: redactle
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.
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
Great site! Cheers! car recovery near me
I like this site! I get a lot of information.
Awesome site! Thanks!
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
I am always searching for informative information like this. We from rehabilitacion fachada valladolid are looking forward to more updates from this site.
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.