<p>I am using Kubernetes. I have two pods.</p>
<p>In one pod, it is running a server. Here is the part of codes trying to connect PostgreSQL service in another pod.</p>
<pre><code>import (
    &quot;context&quot;
    &quot;github.com/jackc/pgx/v4/pgxpool&quot;
    &quot;github.com/rs/zerolog/log&quot;
)

databaseURL := &quot;postgres://admin:passw0rd@my-database-service.hm:40072/my_db&quot;
pg, err := pgxpool.Connect(context.Background(), databaseURL)
if err != nil {
    log.Error().Err(err).Msg(&quot;conn.Close&quot;)
    return nil
}
</code></pre>
<p>Currently, above code gives the error</p>
<blockquote>
<p>{&quot;level&quot;:&quot;error&quot;,&quot;error&quot;:&quot;failed to connect to <code>host=my-database-service.hm user=admin database=my_db</code>: dial error (dial tcp 10.43.140.140:40072: connect: connection refused)&quot;,&quot;time&quot;:1627849943,&quot;message&quot;:&quot;conn.Close&quot;}</p>
</blockquote>
<p>However, after I ssh into the server pod, I can successfully connect the PostgreSQL pod by <code>psql</code>.</p>
<pre><code>/usr/src/app # psql --host=my-database-service.hm --port=40072 --dbname=my_db --username=admin --password
Password: 
psql (13.3)
Type &quot;help&quot; for help.

my_db=# 
</code></pre>
<p>I tried to restart my server pod to make sure it runs after PostgreSQL database is ready, and still got same error.</p>
<p>Any suggestion for further debugging would be helpful. Thanks!</p>
<hr />
<p><strong>UPDATE</strong></p>
<p>I am actually using Linkerd. Might be related with</p>
<p><a href="https://linkerd.io/2.10/features/protocol-detection/" rel="nofollow noreferrer">https://linkerd.io/2.10/features/protocol-detection/</a></p>
<p>I tried to change the PostgreSQL to default port 5432, but still have issue. Will update if find the solution.</p>

Hongbo Miao
<p>After some experiments, I can confirm my issue is not related with Linkerd.</p>
<p>I think my PostgreSQL containerPort/targetPort is still using the default 5432. And it exposed by ClusterIP inside of the network by port 40072, which is why I don't need <a href="https://linkerd.io/2.10/features/protocol-detection/#marking-a-port-as-opaque" rel="nofollow noreferrer">mark the port as opaque</a> in Linkerd.</p>
<p>It turns out that after adding <code>os.Exit(1)</code>,</p>
<pre><code>pg, err := pgxpool.Connect(context.Background(), databaseURL)
if err != nil {
    log.Error().Err(err).Msg(&quot;conn.Close&quot;)
    os.Exit(1) // &lt;- this helps
}
</code></pre>
<p>my Kubernetes will help restart the server pod when it fails initially to wait the PostgreSQL is ready.</p>
<p>After a few times restarts, the server pod can connect PostgreSQL well now.</p>
<p>I think if I manually restarts more times early, it might help too. But definitely not reliable like this way letting Kubernetes to help restart.</p>
