Last active
January 29, 2018 07:50
-
-
Save mattparlane/1ae140905cd3f0a79cf730626ca0fa65 to your computer and use it in GitHub Desktop.
Add containers to host's /etc/hosts file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
require 'hosts' | |
loop do | |
hosts = Hosts::File.read('/etc/hosts') | |
host_elements = hosts.elements | |
all_aliases = [] | |
`docker ps`.split(/\n/).each do |line| | |
cols = line.split(/\s/) | |
next if cols[0] =~ /[^a-f0-9]/ | |
inspect = `docker inspect #{cols[0]}` | |
JSON.parse(inspect)[0]['NetworkSettings']['Networks'].each do |name, settings| | |
ip = settings['IPAddress'] | |
next unless settings['Aliases'] # Container might be running with "network_mode: host" | |
settings['Aliases'].each do |_alias| | |
all_aliases << _alias | |
comment = "Docker: #{_alias}" | |
existing = host_elements.select { |e| e.respond_to?(:comment) && e.comment == comment } | |
if existing.empty? | |
new_element = Hosts::Entry.new(ip, _alias, comment: comment) | |
hosts.elements << new_element | |
else | |
existing.each do |element| | |
element.address = ip | |
end | |
end | |
end | |
end | |
end | |
# Remove old Docker containers | |
hosts.elements.each do |element| | |
next if !element.respond_to?(:comment) || element.comment !~ /Docker: / | |
_alias = element.comment.match(/Docker: (.*)/)[1] | |
next if all_aliases.include?(_alias) | |
hosts.elements.delete(element) | |
end | |
hosts.write | |
sleep 5 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a quick-and-dirty script that should be run on a Docker host to add containers' IP address to the host's /etc/hosts file. It needs to be run as root, obviously. I know Docker has an API, but this works well enough for me.
It relies on the hosts gem:
gem install hosts
Please let me know what you think!