Accessing Postgres on Localhost from Docker Container [duplicate] - postgresql

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(40 answers)
Closed 4 months ago.
I have a dockerized Go application from which I am trying to access Postgres which is running on localhost (outside the container). When I execute docker run image_name, the following error is thrown:
failed to initialize database, got error failed to connect to host=127.0.0.1:5432 user= database=: hostname resolving error (lookup 127.0.0.1:5432: no such host)
Then Go panics and the application exits.
I use the following to access Postgres:
In main.go:
_ = pflag.String("postgresdb-addr", "host=127.0.0.1:5432 user= database=", "connection string for postgres")
`dbAddr := d.cfg.Get("postgresdb-addr")
session, err := gorm.Open(postgres.Open(dbAddr.(string)), &gorm.Config{})
if err != nil {
return fmt.Errorf("unable to open PostgresDB: %w", err)
}`
I am using a Docker file to build and run the Go application and when the docker run command executes, it fails and exits because of the Postgres connection failure issue. My Docker file has no mention of Postgres. Postgres is running on localhost outside the container.
Any help would be greatly appreciated. Thanks.

Instead of localhost, use host.docker.internal to refer to your local machine.

Related

I cannot connect local pgadim to a container that runs postgres

i have an issue
i have a container that has a web application running and a postgres db, when i launch the webapp is connected in database correctly, but when in local i tried using a pgadmin that is install on my machine and i try to connect to database of container it gives me an error connection
error message
TIPS
the container has the port-forward of database
i tried using both localhost and the ip of container as host when initialize connetion using pgAdmin
I have no idea how to do that, someone can help me

Unable to access mongodb running in a docker from local machine

I am trying to access the mongodb running in a docker from my local machine however I am seeing this error message:
Error: couldnt connect to server localhost:27017, connection attempt failed: SocketException: Error connecting to localhost:27017 (127.0.0.1:27017) :: caused by :: No connection could be made because the target machine actively refused it.
commands tried to used to access mongo on my local machine:
mongo localhost:27017
mongo 172.17.0.2:27017(container's ip)
command used to run mongodb on docker
docker run -d -p 27017:27017 mongo:latest
Please advice. Thank you.

how to connect pgadmin container to host system localhost postgres [duplicate]

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(40 answers)
Closed 1 year ago.
I pulled pgAdmin4 docker image into my linux debian machine and followed the process specified here to configure the container. I run docker run -p 8000:8000 --env-file ./pgadmin_docker_env.list -d dpage/pgadmin4. For clarity, the pgadmin_docker_env.list specified in the command contains the environmental variables:: PGADMIN_DEFAULT_EMAIL=my_email#example.com PGADMIN_DEFAULT_PASSWORD=my_password. With the container running in detached mode, I run localhost:8080 in my web browser to access pgAdmin 4 in server mode. However, I was unable to create a server connection to the localhost postgres database from inside the pgadmin. I got the following error after input of the connection parameters (shown in the screenshot attached below)
Unable to connect to server: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
UPDATE
I used host.docker.internal in place of localhost but I still got an error
Unable to connect to server: could not translate host name "host.docker.internal" to address: Name does not resolve
You can skip a step if you've already done it
Using psql, alter the authentication credential of default postgres user, postgres with the following commands
sudo -u postgres psql
ALTER USER postgres PASSWORD 'newPassword';
Optionally, you can also create a user for your current account as a superuser with CREATE ROLE user_name WITH LOGIN SUPERUSER CREATEDB CREATEROLE REPLICATION;
Modify /etc/postgresql/13/main/pg_hba.conf and add
host all all 0.0.0.0/0 md5 to the end of the file
Modify the pgadmin_docker_env.list file to include your choice port
PGADMIN_LISTEN_PORT=8000
Stop the previously running container pgadmin docker stop pgadmin and remove the containerdocker rm pgadmin. Then run docker run --env-file ./pgadmin_docker_env.list --network="host" --name pgadmin dpage/pgadmin4 to run the container in host network mode. See more on host network mode
Run localhost:8000 in your web browser and create a server connection using the same connection parameter as in the screenshot.
localhost in this scenario refers to the PgAdmin container, where there is not a Postgres instance running.
You want to connect to Postgres running on the host machine from the container (from what I can tell anyway?) so use host.docker.internal instead of localhost.

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;
Host=/var/run/cloudsql/project:region:server;
Database=mydb;
Port=5432
";
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" \
"myimage"
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?

couldn't connect to server 127.0.0.1:27017 when trying to run mongo command using docker

I'm trying to run a mongo script on a docker container using this command
docker run --rm -it --volume "$(pwd):/scripts" mongo:latest mongo /scripts/${SCRIPT_FILE_NAME}, and I'm keeping getting this error:
MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect#src/mongo/shell/mongo.js:362:17
#(connect):2:6
exception: connect failed
exiting with code 1
The docker run command that you shared attempts to execute explicitly the mongo /scripts/${SCRIPT_FILE_NAME} command, immediately when the container is started.
At that point in time, the mongodb daemon isn't ready to accept connections(yet).
Instead of trying to initialize manually, you should leverage the built-in mongo mechanism that discovers the scripts under /docker-entrypoint-initdb.d and executes them when the DB is running.
When a mongo container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order.
.js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.
Check the mongo image official documentation for more details.