How to point a hostname to an ip address

I have a running webserver, that can be called via http://localhost:9000/. What I am trying to archive is, instead of calling http://localhost:9000/, I would like to call http://repo.sweetsoft/. 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.sweetsoft

As you can see, I've added the last line but it does not work. What am I doing wrong?


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.sweetsoft

and try to open http://repo.sweetsoft/ 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).

Check OSI model

enter image description here

OSI vs TCP/IP model

enter image description here

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:

  1. Running your application on port 80. Fixes your issue and removes any ambiguity.
  2. 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
  1. 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:9000

If 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.