0

I have a bash script runmydocker.sh that should grab the DNS string sent by the developer, when running he runmydocker.sh and create a new DNS inside the /etc/hosts dynamically and point to the docker server.

This is the flow:

  • grab the DNS sent by the user and store it into a MYDNS variable
  • copy the content of the current hosts
  • insert 127.0.0.1 $MYDNS
  • call docker run ....

So the user should do something like that:

./runmydocker.sh mysite.com

And when it write the URL mysite.com it should be using the docker server.

So my question here is how to insert this new DNS into /etc/hosts?

  • What is a DNS? DNS is the Domain Name System; there is only one of it for the entire Internet. Do you mean a fully qualified domain name (FQDN)? – AlexP Nov 20 '17 at 23:57
  • Thing is you need root permission (sudo) to write to the file /etc/hosts. A simple example of the action would be like: sudo echo x.x.x.x newsite.com >> /etc/hosts. Of course you could embed such a line in your script and start your script from crontab as root, but whether that is the safest solution.... – user680858 Nov 21 '17 at 0:05
1

Assuming your script runs as root, you could do:

sed -i '/^127\.0\.0\.1\s/s/$/ '"$1"'/' /etc/hosts

$1 is the first argument to the script (mysite.com for the example in the question). This command looks up the line containing 127.0.0.1 in the hosts file and appends the new domain to it.

You shouldn't add multiple lines with 127.0.0.1, it could potentially cause problems.

A better way is what the Ubuntu installer does - add a new address in the loopback range (127.0.1.1, for example). That's going to be trickier, since you'll need to find out the last loopback address added and increment it. I'll add a method for that if I find something simple enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.