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.
Hey thanks for this!
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
Yes, right! sand blaster
I really enjoy reading and also appreciate your work. production company near me
Same here! skip hire near me
Likewise!
I appreciate the hard work that has gone into this. Aberdeen fencing
Same here! Really good. Car recovery service
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.
Same here! Really thankful! Sandblasting in Liverpool
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
Really good stuff. I agree! polished concrete birmingham
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.
Thanks for this tutorial! The script you gave worked for me.
Awesome blog. I have read and thought about what you said. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!Biker Boyz Yellow Jacket
This blog have provided valuable information on a topic that is very useful for me and others. Thanks for sharing your ideas.nike tiffany jacket
Nice blog. Keep up the good work.
https://tallahasseeplasticsurgery.net
That’s an awesome article you posted. Read more on this link https://www.tejadosyfachadasantander.com/instalacion-de-canalones. I will come back to read some more.
Very useful tutorial to not have to stop running all your docker containers while updating your /etc/host.
Really good information. Keep it up! skip hire walsall
Actually, it’s pretty good to see! Tiler Adelaide
Thanks for sharing! Tiler Adelaide
Thanks for letting us know! Tiler Wollongong
Good to know about this! Tilers Wollongong Shellharbour
Excellent post! Concreters in Wollongong
Thanks for sharing this to public! Adelaide Landscaping
Such a great post! Glenelg North
I visited Your blog and got a massive number of informative articles. I read many articles carefully and got the information that I had been looking for for a long time. Hope you will write such a helpful article in future. Thanks for writing.Tilers in Hobart
Very useful and informative post! Tiling Townsville
Thats what I was looking for! Flagstaff hill Air conditioning
Very informative post! tiler melbourne
To be honest, I generally don’t read. But, this article caught my attention.seo adelaide
I am really impressed with your writing style. Keep it up! Landscapers Canberra
Many thanks for sharing this! Adelaide Coolroom Hire
Thanks for sharing! Sliding Doors Adelaide
It’s so kind of you! Solar Panels Adelaide
Many many thanks to you! Cleaning Services Adelaide
You presented your ideas and thoughts really well on the paper. Solar Panels Adelaide
What a great piece of article! seo adelaide
Very informative content. Thanks. tow truck wollongong
Please keep up the good work! drum lessons adelaide
Thanks for letting us know. Tiler Adelaide
I thik this is very helpfull post Canberra landscapers
Great Post! I learned a lot from this, Thank you! Canberra landscapers
Really nice article and helpful me Canberra landscapers
Nice article, waiting for your another Canberra landscapers
Your suggestion to use a script to automate this task is very useful and will certainly save time and effort. One more thing, are drywall and sheetrock the same thing?
This tutorial is really helpful and practical to follow.
This is very useful. Google
Great stuff here! Click here to get in touch with the best sandblaster in Manchester.
Awesome site!
Great work! Keep it going.
I definitely agree with this post!
This post is really informative and helped me with understanding how to update my hosts.
Thanks for sharing this amazing and easy to follow tutorial. I can now update my host even if the docker containers are running.
You made those functions so easy!
Helpful blog! Thanks for this. roadside recovery
I was able to use the script you provided. Plumber Abbotsford
Hello, I read the post well. 카지노사이트 It’s a really interesting topic and it has helped me a lot. In fact, I also run a website with similar content to your posting. Please visit once
Really good blog! car recovery
Awesome blog!
Appreciate this.
Thanks!
I love this!
Excellent post!
I’m glad I found this!
I feel grateful for this!
In this way, we can use the name that we have given it in docker together with «.docker.local» to refer to the container and call a service enclosed in it. For example, to connect to the mariadb-proyectos.docker.local database we can, from the same host computer: But wait, who is the best drywall company?
Great site! plymouth car recovery
Excellent weblog, great work. Your idea couldn’t have most certainly been written any better. House Painters Red Deer
Thanks for showing us how to update /etc/hosts while dockers are still running so we do not need to stop them just to update.
Really fantastic site! Recovery Slough
Thanks for this blog! Lots of info. resin driveway
Thanks for writing a detailed information
I always like to read a quality content having accurate information regarding the subject and the same thing I found in this post. Nice work
Grease T Birds Jacket
Exceptional and lovely post. Everyone will benefit from it. I appreciate you sharing this fantastic post. It really helps me out a lot. Spy Jacket
Hi, after reading this awesome piece of writing i am too glad to share my knowledge here with colleagues. Roofing Victoria BC
Yeah same here! Recovery truck
«Thank you very much for this wonderful topic!
»
https://elpasoplasticsurgery.net
The article you linked to above was interesting to read and did a great job of explaining everything. [url=https://www.liqteq.com/]Liquid Technologies[/url]
The article you linked to above was interesting to read and did a great job of explaining everything. Liquid Technologies
This is so interesting to learn about.
Please note that modifying system files such as /etc/hosts requires administrative privileges, so you may need to enter your password when prompted. | https://www.charlottedrywallpros.com
Thanks for this! 4 yard skip
QuickBooks offers integration with Square, allowing you to sync your Square transactions and sales data directly into QuickBooks. This integration can help streamline your accounting processes and keep your financial records up to date. Here are some key points about quickbooks integration with square
Awesome blog! skip sizes
Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a book from our area library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there. شيخ روحاني
Great article!
Really good!
This is very helpful!
Great job on this tutorial!
I’m grateful for your help!
This is awesome!
So good!
Proud of this!
Great information.
I have to say that this is great information!
I hope to know more.
Great you have this here.
You made this very interesting!
So good!
You made this very interesting
Thank you
I’m impressed by the talents here.
Been looking for this tutorial!
Glad I found this!
Really awesome!
Will surely recommend this.
This is worth sharing!
Wow! A great solution.
Very impressive post!
Got it! Thanks
Will surely share this
I admire your excellence!
Please note that modifying system files like /etc/hosts may require administrative privileges, so make sure you run the script with appropriate permissions.
Great find!
Happy you shared this.
I find this very helpful.
Appreciate your effort putting out such an interesting content.
This is an ideal tutorial.
This is highly recommended post!
Very impressed by how you cleared this thing up.
There’s a lot to learn here.
Really good
I do think that this is very relevant post!
Great information as always!
Quordle has been available for purchase for a span of five months. Its successful outcome is the result of being released as an incomplete product. The daily game mode presents a fresh set of words for the Quordle puzzle every day at the stroke of midnight.
Quordle Today
I find this very interesting!
Great post!
Love this!
Great work!
Wonderful!
Really appreciate this!
This is a great find.
Great job on this folks!
Good thing I found this.
I’m also thankful for this great article!
Happy to discover this!
Hope to know more
Got this!
I’d love to share this.
This is 100% beneficial!
Thanks for sharing this technique on how to update without having to stop all your running docker containers.
I read your blog, I think you have a lot of ideas, from your post let me try to perfect myself, I little by little to read your thoughts, let me shock, I see your excellence, your post will help many people like me lost.토토사이트
Great article. Really good!
play4doge.com the best place to play with doges
ufa168 vip UFABET 357 เว็บคาสิโนสุดปัง พาคุณเข้าสู่เส้นทางเศรษฐี
I’m pretty pleased to find this website. I want to to thank you for your time due to this wonderful read!! I definitely really liked every part of it and i also have you book marked to look at new stuff in your site. My Site: Tennis Betting
Actualizar el archivo /etc/hosts con los contenedores Docker en ejecución es esencial para establecer una comunicación fluida en un entorno de desarrollo. Automatizar este proceso puede ahorrar tiempo y evitar errores. Recuerda utilizar herramientas como Docker API o scripts personalizados para mantener actualizada esta configuración crucial. Elizabeth Ferber
To run the script, you can save it as a file called update_hosts.py and then run it from the command line:
python update_hosts.py
This will update your /etc/hosts file with all docker containers running. You can then access the services running in each container by their hostname. For example, if you have a container running with the hostname my-container, you can access it by typing localhost:8080 in your browser.
Tempest Hosting
Your blog makes people feel refreshed after reading it. I will be happy to see your words, and I hope more and more people will also feel this joy when they see it. Your writing is great, and I would like you.검증사이트
Hey thanks for [url=https://www.example.com/]sharing[/url] it with us and keep up the good work
Thank you!
Appreciate the help!
Love this.
This is excellent.
This is worth sharing
Really awesome!
I’m impressed with this blog
Great thing you made this blog!
You made this very interesting!
Very well written
I’m glad you wrote about this article.
Got this!
I’d love to know more.
This is so good.
Looking forward for more.
Wonderful blog!
Really nice article
This is a great position. This article provides truly high-quality information. I will definitely investigate. Here are very useful tips. Thank you very much. Keep working hard 토토사이트
The UFABET website has a world-class safety standard. More than 10 levels of data protection, customers do not have to worry about personal data security. Online football betting is supported through the internet And online casinos with more than 1000 games to choose from, as well as live casinos 24 hours a day with many promotions.
I am constantly amazed at the amount of information available on this subject. What you have presented is well researched and well expressed to convey your position on this to all readers. With this data, I will study it further Thank you so much for posting such a good comment.. 먹튀신고