npgsql can't connect to a Unix socket from inside container


I started a process on the host that listens on a Unix socket: /cloud_sql_proxy -enable_iam_login -dir=/var/run/cloudsql -instances=project:region:server

I confirmed I can make a connection with psql: psql "sslmode=disable host=/var/run/cloudsql/project:region:server user=myuser@project.iam dbname=mydb

I need to connect to Postgres over this socket with npgsql but inside a container.

I'm using this connection string:

string DBConnectionString = @"
User ID=myuser@project.iam;

using (var connection = new NpgsqlConnection(DBConnectionString))
    connection.Query("SELECT * FROM mytable ORDER BY zzz");

Running this application locally on the host with this connection string works as expected- it can connect to the Unix socket and query the DB without issue. From inside a container it is not working.

I start the container trying to mount the file for the Unix socket:

docker run \
    --mount type=bind,source="/var/run/cloudsql",target="/var/run/cloudsql" \

But I'm getting this error:

[00:13:46 FTL] Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (111): Connection refused /var/run/cloudsql/project:region:server/.s.PGSQL.5432
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)

When I look at the process using the socket (cloud SQL proxy) I see no output during the attempt. When to connect to the socket from the host with the app or psql I see logs for login attempts. So maybe the socket isn't mounted correctly?

Update: also works fine with k8s

Just to add to this, this also works in k8s. In my manifest I just create a shared volume. I have a container running the app and another container running the cloud SQL proxy and mount the volume to both and it just works. So I'm wondering if this is some local docker perms issue or something?

asked on Stack Overflow May 5, 2021 by red888 • edited May 13, 2021 by halfer

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0