How to point a hostname to an ip address
I have a running webserver, that can be called via . What I am trying to archive is, instead of calling , I would like to call . I've tried to modify the hosts file as follow:
127.0.0.1 localhost
127.0.1.1 sweetsoft
127.0.0.1:9000 repo.sweetsoftAs you can see, I've added the last line but it does not work. What am I doing wrong?
22 Answers
There is a misunderstanding about hosts file here.
First of all, hosts file have precedence over DNS on most operating systems, you can define them on Linux/Unix operating systems and macOS in /etc/hosts and c:\windows\system32\drivers\etc\hosts on Windows.
So when you add a record in your hosts file like:
127.0.0.1 repo.sweetsoftand try to open in your browser, it doesn't send any DNS query to the outside world and uses this entry from your hosts file.
Keep in mind this only works for A record (resolving a name or domain address to an IPv4 address) and AAAA record (resolving a name or domain address to an IPv6 address) and you can not define TXT or MX records for example.
But port numbers are in a different network layer, hosts file only understands names (like repo.sweetsoft) and IP addresses, it's layer 3 and 4 in ISO model (Network/Transport) but port numbers are in layer 7 (application layer).
Since hosts file or DNS protocol are not aware of application layers, they have no idea about port numbers too.
Your configuration by adding 127.0.0.1:9000 to your hosts file is like adding port numbers to DNS A records.
After this clarification, you can fix this issue in multiple ways:
- Running your application on port 80. Fixes your issue and removes any ambiguity.
- Forward port 80 to port 9000 on your machine via iptables
# This command will forward all requests destined to port 80 and makes a lot of conflicts, I suggest socat
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-ports 9000- Forward port 80 to port 9000 on your machine via socat:
apt install socat -y
socat TCP-LISTEN:80,fork TCP:127.0.0.1:9000If you can't change your application port, socat will be the easiest way.
For day to day usage, you can write a systemd service file to run it in the background.
You can go with a different approach:
127.0.1.1 sweetsoft repo.sweetsoftin/etc/hosts- Direct
repo.sweetsoft:80and127.0.0.1:9000in your HTTP server (AFAIK, Apache can make it usingVirtualHostReference).
However, it seem to me you are using an app development server. Using Apache to proxy may be an overkill.