Override DNS with /etc/hosts
Tell your computer which IP address to use for a hostname with the /etc/hosts. Handy for development and other scenarios.
scenario 1
The other day we needed to fix some issues on one of our servers. We removed the instance from the Load Balancer, made the changes, and then went to verify. The problem is that we enforce SSO/SAML authentication per client and select the configuration based on hostname. For example <client>.<application>.com. This is matched on the whole hostname, not just the prefix. When accessing the instance directly we use a different internal hostname and so the application does not know which SAML config to use.
We were able to quickly work around this by pointing the hostname we want to the instance IP we need in the /etc/hosts file.
<instance-ip> <client>.<application>.com
scenario 2
I have also used the same technique recently for local development. I set up a single node MicroK8s instance in my local network. At the time this server was not accessible from the public internet, but I still want to setup HTTPS in preparation. I created self signed certificates using the desired (future) hostnames. When I navigate to the machines IP address in the browser I get HTTPS errors because the hostname doesn't match what is in the certificate. I get around this issue by adding entries to the /etc/hosts file.
<target-ip> application1.mydomain.com
<target-ip> application2.mydomain.com
<target-ip> a-different-domain.com
Now when I navigate to application1.mydomain.com I am now connected to the machine in my local network and the certificate matches the hostname.
Note: For the browser to trust a self signed certificate without adding exceptions you may need to add the Certificate Authority to the browser Certificate Store. This may not work in Firefox which now appears to reject Self Signed Certificates.
scenario 3
Your micro-services generally run in a Docker Network or Kubernetes and you connect to each host by its service name e.g. mysql://mysql-service:3306. In our applications this kind of thing is always configurable either via environment variables or config files. An alternative to this would be to add the entry into the hosts file.
127.0.0.1 mysql-service
This can be handy if you don't want to modify config files or aren't setup to use environment variables. In our case we generally set env vars in our IDE on a per project basis. If the only thing we actually need to configure is the host, then this solution could be a good alternative.