Why is supplying the hostname sometimes optional and otherwise not in psql?
The default for all Postgres command line tools is to use &quot;local&quot; connections, i.e. unix sockets (unless this is &quot;overruled&quot; by environment variables).
The next step in the authentication process is to look up if and how the user should authenticate - which is defined by the entries in pg_hba.conf.
Most probably the default entry in pg_hba.conf says &quot;all local connections are authenticated using peer&quot; which is the default and is controlled by the following line:
local   all             all                                     peer

So psql -U teamcity tries to use a &quot;local&quot; connection and pg_hba.conf requires peer authentication for the user teamcity - most probably your current Linux user is not named teamcity and thus the authentication fails.
If you add -h localhost to the command line, a &quot;host&quot; connection using TCP is established, which is controlled by a different set of rules in pg_hba.conf.  Maybe our file contains something like:
host    all             all             all                     md5

which allows TCP connection from any client if, with any database user as long as the correct password is provided.
You probably ran createuser and createdb while being logged in as the postgres Linux user, and for that peer authentication succeeds as the Linux username matches the Postgres database username.