Skip to content

Instantly share code, notes, and snippets.

@mattparlane
Last active January 29, 2018 07:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattparlane/1ae140905cd3f0a79cf730626ca0fa65 to your computer and use it in GitHub Desktop.
Save mattparlane/1ae140905cd3f0a79cf730626ca0fa65 to your computer and use it in GitHub Desktop.
Add containers to host's /etc/hosts file
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
@mattparlane
Copy link
Author

mattparlane commented Jul 4, 2017

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment