Using Docker to launch web app, can't connect to Postgresql DB? - postgresql

I received the following error when trying to write session data using Tomcat's PersistentManager to a Postgres DB running on my local machine:
SEVERE: A SQL exception occurred org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
The application itself runs in a docker container. For completeness sake, my current context.xml file is:
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Manager className="org.apache.catalina.session.PersistentManager"
distributable="true" processExpiresFrequency="6" maxIdleBackup="0" debug="99" >
<Store className="org.apache.catalina.session.JDBCStore"
driverName="org.postgresql.Driver"
connectionURL="jdbc:postgresql://localhost/admin?stringtype=unspecified"
connectionName="admin" connectionPassword="admin"
sessionAppCol="app_name" sessionDataCol="session_data" sessionIdCol="session_id"
sessionLastAccessedCol="last_access" sessionMaxInactiveCol="max_inactive"
sessionTable="tomcat_sessions_tb" sessionValidCol="valid_session" />
</Manager>
</Context>
Pursuant to the suggestions here: Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
I confirmed via a netstat -aln | grep LISTEN that Postgresql is running and listening on the correct ports:
tcp4 0 0 127.0.0.1.5432 *.* LISTEN
tcp6 0 0 ::1.5432 *.* LISTEN
and that my postgresql.conf (located in usr/local/var/postgres) has listen_addresses = localhost and port = 5432, which mirrors the host and port of my running server in Pgadmin3.
I suspect that the problem is that Docker runs in a VM, and thus the local information I have obtained may not be the whole story. Reading up on the available information online, it seems that I may require some sort of bridged networking.
However, I admit I am a novice in this area, and I'm unsure of how to set it up.

Why I can NOT connect to localhost:5432?
Cat your container's /etc/hosts
$ sudo docker exec -it [container] cat /etc/hosts
For docker networks is bridge by default, the localhost inside points to container itself(Docker default bridge network).
Then you don't have 5432 listening in your container:
$ sudo docker exec [container] nc -v -z localhost 5432
Solution 1. If you wanna hardcode the "localhost:5432" inside your config xml, the easiest way is creating your container with the option "--net=host":
$ sudo docker run --net=host -it ...
Solution 2. Change the localhost of your docker host ip inside the container
Get your docker host ip๏ผš
$ sudo docker inspect -f '{{ .NetworkSettings.Gateway }}'
192.168.5.1
Enter your container:
$ sudo docker exec -it [container] /bin/bash
Edit the file /etc/hosts to point the localhost to docker host ip:
$ sudo vim /etc/hosts
192.168.5.1 localhost
Solution 3. Modify your db config file to use an alias instead of localhost:
connectionURL="jdbc:postgresql://DB_ALIAS/admin?stringtype=unspecified"
Then add the DB_ALIAS to the container's hosts :
$ sudo docker run --add-host DB_ALIAS:192.168.5.1 -it [image] ...

If you are using docker-compose together with postgres image, than you can reuse service name as IP inside jdbc connection (here: app-db)
web:
build: ./web
ports:
- "8080:8080"
links:
- app-db
environment:
- MYAPP_JDBC_URL=jdbc:postgresql://app-db:5432/somedb
- MYAPP_JDBC_USER=someuser
- MYAPP_JDBC_PASS=pass
app-db:
image: postgres:9.6
environment:
- POSTGRES_USER=someuser
- POSTGRES_PASSWORD=pass
- POSTGRES_DB=somedb
expose:
- 5432
volumes_from:
- app-db-data
app-db-data:
image: cogniteev/echo
command: echo 'Data Container for PostgreSQL'
volumes:
- /opt/postgresdata/:/var/lib/postgresql/data

The best decision!
jdbc:postgresql://host.docker.internal:5432/somedb
Don't thank.

I had to expose port with -p 5432:5432:
docker run --name postgres -e POSTGRES_PASSWORD=secret -d -p 5432:5432 postgres

I was getting the same error but this simple solution works perfect for me.
sudo docker run -d --net="host" -it <IMAGE>
Now I can run my app https://x.x.x.x:pppp/../.. and everything works fine. I hope this helps

Related

Hasura container cannot connect to postgres DB?

I am running a postgres db running in Docker with:
docker run -d -p 5432:5432 --name db --env POSTGRES_PASSWORD=postgres --env POSTGRES_USER=postgres postgres
I'm trying to connect Hasura to it, with this command
docker run --name hasura -p 5002:8082 --env HASURA_GRAPHQL_DATABASE_URL=postgres://postgres:postgres#localhost:5432 -e HASURA_GRAPHQL_ENABLE_CONSOLE=true hasura/graphql-engine:latest
but I get this response:
{"type":"startup","timestamp":"2021-04-20T05:49:08.548+0000","level":"info","detail":{"kind":"server_configuration","info":{"live_query_options":{"batch_size":100,"refetch_delay":1},"transaction_isolation":"ISOLATION LEVEL READ COMMITTED","plan_cache_options":{"plan_cache_size":4000},"enabled_log_types":["http-log","websocket-log","startup","webhook-log"],"server_host":"HostAny","enable_allowlist":false,"log_level":"info","auth_hook_mode":null,"use_prepared_statements":true,"unauth_role":null,"stringify_numeric_types":false,"enabled_apis":["metadata","graphql","config","pgdump"],"enable_telemetry":true,"enable_console":true,"auth_hook":null,"jwt_secret":null,"cors_config":{"allowed_origins":"*","disabled":false,"ws_read_cookie":null},"console_assets_dir":null,"admin_secret_set":false,"port":8080}}}
{"type":"startup","timestamp":"2021-04-20T05:49:08.548+0000","level":"info","detail":{"kind":"postgres_connection","info":{"retries":1,"database_url":"postgres://postgres:...#localhost:5432"}}}
{"type":"pg-client","timestamp":"2021-04-20T05:49:08.548+0000","level":"warn","detail":{"message":"postgres connection failed, retrying(0)."}}
{"type":"pg-client","timestamp":"2021-04-20T05:49:08.548+0000","level":"warn","detail":{"message":"postgres connection failed, retrying(1)."}}
{"type":"startup","timestamp":"2021-04-20T05:49:08.548+0000","level":"error","detail":{"kind":"catalog_migrate","info":{"internal":"could not connect to server: Connection refused\n\tIs the server running on host \"localhost\" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\n","path":"$","error":"connection error","code":"postgres-error"}}}
{"internal":"could not connect to server: Connection refused\n\tIs the server running on host \"localhost\" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\n","path":"$","error":"connection error","code":"postgres-error"}
I am running Docker Desktop v3.3.1 on Windows 10.
Any help on this would be appreciated.
Thanks.
As anemyte mentioned, changing localhost to host.docker.internal works for me.

PgAdmin Connecting to Postgres through Docker-compose results in "Unable to connect to server : timeout expired" [duplicate]

I have created an ubuntu image with nginx, php and postgres.
I want to connect the postgres database in my current image with pgadmin located on my local machine.
I have tried using docker inspector to try to use the image ip to make a connection with my local pgadmin but without much success. I've also tried configuring some ports on local to make connection work.
It's a valid question don't know why people feel "doesn't seem possible to answer that question".
So, here's how I do what you are trying to do:
Pull postgres image from Docker Hub
docker pull postgres:latest
Run the container using the below command
docker run -p 5432:5432 postgres
Using docker's inspect command find the IP
Use that IP, PORT, Username, and Password to connect in PGADMIN
You can also do a simple telnet like below to confirm if you can access docker postgres container:
telnet IP_ADDRESS 5432
1. Postgres with Docker
docker run \
-p 5432:5432 \
--name container-postgresdb \
-e POSTGRES_PASSWORD=admin \
-d postgres
2. PgAdmin with Docker
docker run \
-p 5050:80 \
-e "PGADMIN_DEFAULT_EMAIL=name#example.com" \
-e "PGADMIN_DEFAULT_PASSWORD=admin" \
-d dpage/pgadmin4
3. Connection string for PgAdmin
Enter PgAdmin on localhost:80. Then add a server with:
name: container-postgresdb
host: host.docker.internal
database: postgres
user: postgres
password: admin
You can also use this to find out the host address โ€” it will be listed as IPAddress in the output โ€”:
docker inspect container-postgresdb \
-f "{{json .NetworkSettings.Networks }}"
This other article might help with more info.
What I have done success on windows 10 running docker for windows 1.12.6(9655), the step is like below:
Pull the latest postgres
docker pull postgres:latest
run the postgres containner:
docker run -d -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password123 --name db-my -p 5432:5432 --restart=always postgres
Then installed the latest version of pgAdmin4 from
pgadmin website
Run pgAdmin 4 create new server, and input as following
Host: 127.0.0.1
Port: 5432
User name: user
password: password123
Then everything is ok, connect to docker postgres instance success.
Alternatively, you could combine Postgres and Pgadmin in one docker-compose file, and login as user pgadmin4#pgadmin.org, pwd: admin. To add the Posgres server, use hostname postgres, port 5432.
version: '3'
services:
postgres:
image: postgres
hostname: postgres
ports:
- "6543:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: TEST_SM
volumes:
- postgres-data:/var/lib/postgresql/data
restart: unless-stopped
pgadmin:
image: dpage/pgadmin4
depends_on:
- postgres
ports:
- "5555:80"
environment:
PGADMIN_DEFAULT_EMAIL: pgadmin4#pgadmin.org
PGADMIN_DEFAULT_PASSWORD: admin
restart: unless-stopped
volumes:
postgres-data:
If you verified that PostgreSQL is running and you can connect there with local copy of PgAdmin...
The answer is simple: use host.docker.internal istead of localhost for the PgAdmin running inside the Docker
In my case I could solve the problem inspecting my postgre image through command
docker inspect CONTAINER_ID | grep IPAddress.
So, I used the docker ip address to config my pgadmin 4 connection and everything was fine. Thanks to #Afshin Ghazi
I included this in the docker yaml file to get the database and pgAdmin:
database:
image: postgres:10.4-alpine
container_name: kafka-nodejs-example-database
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
expose:
- "5432"
ports:
- 8000:5432
volumes:
- ./services/database/schema.sql:/docker-entrypoint-initdb.d/1-schema.sql
- ./services/database/seed.sql:/docker-entrypoint-initdb.d/2-seed.sql
pgadmin:
image: dpage/pgadmin4
ports:
- 5454:5454/tcp
environment:
- PGADMIN_DEFAULT_EMAIL=admin#mydomain.com
- PGADMIN_DEFAULT_PASSWORD=postgres
- PGADMIN_LISTEN_PORT=5454
The postgres username is alphaone and the password is xxxxxxxxxxx.
Do a docker ps to get the container id and then docker inspect <dockerContainerId> | grep IPAddress
eg: docker inspect 2f50fabe8a87 | grep IPAddress
Insert the Ip address into pgAdmin and the database credentials used in docker:
If pgAdmin is intended to be run wihtin same Ubuntu host/guest, then you need to link postgres container, so it could be resolved by a name.
1. Run a postgres container:
docker run --name some-postgres -e POSTGRES_PASSWORD=postgres -d postgres
2. Run pgAdmin container:
docker run -p 80:80 --link some-postgres -e "PGADMIN_DEFAULT_EMAIL=email#domain.com" -e "PGADMIN_DEFAULT_PASSWORD=postgres" -d dpage/pgadmin4
3. Now when adding new server in phAdmin web app, use some-postgres as server name
Note the --link some-postgres when we were bringing up the pgAdmin. This command makes postgres container visible to pgAdmin container.
After facing this issue for two days i was able to resolve that issue.
solution of this problem is already answered by peoples like do inspect
docker inspect CONTAINER_ID
but while running this command i got a-lot of logs like Host Config Config Network Settings etc. so i got confused which IPAddress to add in the pgAdmin connection because i tried 0.0.0.0 and config, host, networkSettings different -2 IPAddress in the logs but finally it works after trying a-lot.
it works with which IP, we have to add that network ip address (which we created to connect the postgres and pgAdmin.)
like in my case when i run :-
docker inspect postgres_container
"NetworkSettings": {
"Bridge": "",
"SandboxID": "sdffsffsfsfsfsf123232e2r3pru3ouoyoyuosyvo8769696796",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"5432/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "5432"
}
]
},
"SandboxKey": "/var/run/docker/231231Ad132",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"postgres": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"postgres",
"0e2j3bn2m42"
],
"NetworkID": "35rhlhl3l53l5hlh3523233k3k4k22l3hk2k4",
"EndpointID":"b3424n43k52o2i4n235k1k4l2l4hj234f14n2",
"Gateway": "192.168.16.1",
"IPAddress": "192.168.16.2",
"IPPrefixLen": 20,
"IPv6Gateway": "",
so we have to add the NetworkSettings -> Network -> Postgres(mine created network) -> IPAddress i.e. "IPAddress": "192.168.16.2".
After adding this ip it will work.
I hope it will help.
This worked for me on Ubuntu 18:
1- Run a postgres container
docker run -d -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password123 --name my-postgres -p 5432:5432 postgres
2- Run a pgAdmin container
docker run --rm -p 5050:5050 thajeztah/pgadmin4
3- Get your local IP (in Ubuntu by ifconfig command)
4- Open localhost:5050 in your browser
5- Click on Servers >> Create >> Server...
6- In General tab, give it a name, for example: docker. In Connection tab, enter these fields:
Host name: The IP from 3
Username: user
Password: password123
7- Click on Save and now everything should work fine.
Note: If this didn't work, try "localhost" for the host name.
In order or find your IP of the container, use following command
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
Referrence: How to get a Docker container's IP address from the host
If you're on a mac and localhost use below as credentials:
version: '3.5'
services:
postgres:
container_name: postgres_container
image: postgres
environment:
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
PGDATA: /data/postgres
volumes:
- postgres:/data/postgres
ports:
- "5432:5432"
networks:
- postgres
restart: unless-stopped
pgadmin:
container_name: pgadmin_container
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4#pgadmin.org}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
PGADMIN_CONFIG_SERVER_MODE: 'False'
volumes:
- pgadmin:/var/lib/pgadmin
ports:
- "${PGADMIN_PORT:-5050}:80"
networks:
- postgres
restart: unless-stopped
networks:
postgres:
driver: bridge
volumes:
postgres:
pgadmin:
Connection:
Hostname/Address: host.docker.internal or 0.0.0.0
Port: 5432
username: postgres
database: postgres
password: changeme
You have to expose the postgres port in the container to you local system. You do this by running your container like this:
docker run -p 5432:5432 <name/id of container>
when connecting with your GUI client or CLI make sure to use the ip-address not localhost even if your ip-address is the localhost ip-address.
docker ps would give you the ip address your postgres container is on.
In my case, I had a PostgreSQL container, so I didn't change my container or create a docker-compose approach, I needed pgadming after few months to had installed PostgreSQL, so this is my approach:
docker inspect my_container_id_postgreSQL
The network assigned to PostgreSQL was:
"Networks": {
"docker_default": {
"IPAddress": "172.18.0.2",
...
}
}
Ran my PGADMIN with --network command.
docker run -p 85:80 --network docker_default -e 'PGADMIN_DEFAULT_EMAIL=user#domain.com' -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' -d dpage/pgadmin4
Insert the Ip address into pgAdmin and the database credentials used in docker.
I hope this can be useful for someone.
Regards.
You can create a Docker bridge network to do this too.
$ docker network create pgnet
a0ae44aaf6f806fc37302e4c603b4828c4edb8d487fd9cd90e2fb19ae1d5c65f
$ docker run --detach \
--name pg \
--network pgnet \
--publish 5432:5432 \
--restart always \
--env POSTGRES_PASSWORD=pg123 \
--volume ${PWD}/data:/var/lib/postgresql/data \
postgres:12.1
b60611e43727dabe483c1f08fdf74961b886ce05b432a10a0625bd1b6db87899
$ docker run --detach \
--name pgadm \
--network pgnet \
--publish 8000:80 \
--volume ${PWD}/pgadmin:/var/lib/pgadmin \
--env PGADMIN_DEFAULT_EMAIL=user#domain.com \
--env PGADMIN_DEFAULT_PASSWORD=pgadm123 \
dpage/pgadmin4:4.20
27f9ce1c1c4c383ee1507f4e2d88f6ef33d4fcf5b209a8a03b87519f90d56312
Open http://localhost:8000/
Click Add New Server
Create - Server
Name: db
Hostname/address: pg
Username: postgres
Password: pg123
Save
The Hostname/address used above is the name of the Postgres container given by --name pg
When you start container you have network alias for it. Just use this alias in pgadmin UI.
Like if you have the following docker compose config:
version: "3.5"
services:
postgres:
container_name: postgres-14
image: postgres:14.1
restart: unless-stopped
ports:
- "5432:5432"
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
- POSTGRES_PASSWORD=root
- POSTGRES_USER=postgres
hostname: postgres
pgadmin:
container_name: pgadmin4
image: dpage/pgadmin4
restart: unless-stopped
ports:
- "80:80"
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
- PGADMIN_DEFAULT_EMAIL=user#domain.com
- PGADMIN_DEFAULT_PASSWORD=admin
hostname: pgadmin
You can add server with hostname: postgres
For macOS IPs of postgres and pgadmin4 are different from the ones docker inspect provides.
Type
docker-machine ls
Take a look at the name of the server on the left. It's default by default.
docker-machine ip default will IP you need to use for both, pgadmin4 in browser and for postgres in pgadmin4 settings.
Are you using Window Subsystem LinuxWSL2 to run Docker and PgAdmin?
The steps I suggested is similar to what folks suggested. In my case I am using window environment
Step 1: Open CMD and type ipconfig and hit enter.
Step 2: Check WSL IPv4 Adress
Ethernet adapter vEthernet (WSL):
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : 3bd9::997b:b52a::fe80::65b3%63
IPv4 Address. . . . . . . . . . . : 172.172.172.1 // use the IP as host/address
Subnet Mask . . . . . . . . . . . : 255.255.255.255
Step 3: Open PgAdmin from the browse and create a server
Step 4:
// Here it depends on your desired config mine is the following
Server: postgres
host address: IPv4 Address(step 2)
username: postgress(username for postgress)
password: password(password for postgress)
I spend two days to figure out what was wrong, I hope someone will find it helpful
If local host port 5432 already in use by another psql servers, change it when creating the container and in Pgadmin.
What I have done success on macOS Monterrey running Docker Desktop for macOS(M1):
Pull the latest postgres:
docker pull postgres
Run the postgres container:
docker run -d -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres --name postgres-server -p 5432:5432 --restart=always postgres
Then installed the latest version of pgAdmin 4 (macOS) from pgadmin website
Run pgAdmin 4 create new server, and input as following Host: 127.0.0.1 Port: 5432 User name: postgres password: postgres
pgAdmin 4: Connection postgres-server
Here are the full steps that worked for me
Download and install pgadmin GUI tool
Run docker container: docker-compose up my-db.
From this command logs, note down ipv4 address and port. In my case, it's 0.0.0.0 and 5432.
Open docker-compose.yml file and note down POSTGRES PASSWORD
open pgadmin gui
enter name
In connection tab:
enter that ipv4 address in Hostname/address
enter that port
enter that POSTGRES PASSWORD in password
save. ๐ŸŽŠ
To find the correct ip for your container, execute the following commands:
Check container ID:
docker ps
To check the correct IP of your container:
docker inspect <ID_CONTAINER> | grep "IPAddress"
The configuration of both PostgreSQL and PgAdmin with Docker are simple, if not right, I recommend redoing the configuration from scratch, if your problem is deeper.
Here is a script I developed to solve this problem.
script-sh/install-docker-postgres-and-pgadmin
I did not connect with my container pg (dpage/pgadmin4 image) from browser on 0.0.0.0:9090 .
I ran this command :
docker run --name pg -p 9090:9090 -e PGADMIN_DEFAULT_EMAIL='faizan' -e PGADMIN_DEFAULT_PASSWORD='faizan' -d dpage/pgadmin4
Solution one :
First I tried to inspect the container for IP address
docker inspect pg
I got the container IP address "IPAddress": "172.17.0.3". http://172.17.0.3:9090 did not accessible.
Solution two :
And then I ran command without de-attached mode (-d removed)
docker run --name pg -p 9090:9090 -e PGADMIN_DEFAULT_EMAIL='faizan' -e PGADMIN_DEFAULT_PASSWORD='faizan' dpage/pgadmin4
# Output, it should be running on 9090.
Listening at: http://[::]:80
-p 9090:9090 did not work.
Finally I found the solution :
On some filesystems that do not support extended attributes, it may
not be possible to run pgAdmin without specifying a value for
PGADMIN_LISTEN_PORT that is greater than 1024. In such cases, specify
an alternate port when launching the container by adding the
environment variable, for example:
-e 'PGADMIN_LISTEN_PORT=5050'
Donโ€™t forget to adjust any host-container port mapping accordingly.
Read more about it official doc
I added -e 'PGADMIN_LISTEN_PORT=9090' and worked for me.
You can try both solutions, it will definitely work for you.
I ran this, It worked for me
docker pull dpage/pgadmin4
docker run -p 9000:80 -e 'PGADMIN_DEFAULT_EMAIL=test#gmail.com' -e 'PGADMIN_DEFAULT_PASSWORD=root' -d dpage/pgadmin4
The solution I tried and worked for me, was to create a docker compose file where I included postgress and pgadmin as services. For more details: Connecting pgadmin to postgres in docker
Tested on Mac
pgAdmin-4: version 6.12
I tried several answers here and in other places but nothing worked for me.
Here is the problem I had and the solution.
I had a docker postgres running my machine and need to connect this server in pgAdmin.
All I need to do was to check the docker information and fill the server configs based on that in pgAdmin.
You can do this by opening your docker and going to dashboard and then selecting the postgres image you're using. There is a tab called Inspect click on that. Here you can get all the information about that postgres container.
Now open the pgAdmin and resister a server by right clicking on the servers -> Register -> Server.
choose a name for the server and click Connection tab.
Here we need to fill the data like host name/address, IP, ports and etc.
In docker Inspect tab, there is Ports section that you can get this data from, something like this:
So your host address based on this picture is 172.0.0.1 and port is 5873.
Other info like database, user and password is also available in Environment section in docker Inspect tab.
Now fill the other information click save in pgAdmin and it should work.
Go to your container terminal on Docker Desktop and type hostname -I in case is linux to get the ip assigned to this machine, then go to your pgAdmin an try it out. #Rigoxls

Can't connect to DB located in docker container

I'm trying to create PostgreSQL DB inside docker container and connect to it from my local machine. Running docker-compose up -d with that inside docker-compose.yml:
version: '3.5'
services:
db:
image: postgres:12.2
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_DB: db
POSTGRES_USER: root
POSTGRES_PASSWORD: root
ended successfully. No crashes, errors of something. But, when I'm trying to connect to it with pgAdmin4 with these credentials:
Host name/address: localhost
Port: 5432
Maintenance database: db
Username: root
Password: root
it says to me:
Unable to connect to server:
FATAL: password authentication failed for user "root"
My OS: Windows 10 build(1809)
PostgreSQL version (installed on local machine): 12
Docker version: 19.03.13, build 4484c46d9d
UPD 1:
After re-creating container with different ports (now it is 5433:5433), pgAdmin4 error changed:
Unable to connect to server:
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
Host name/address: localhost
Port: 5432
You are trying to connect to 5432 port on localhost. Are you sure your container is taking the host IP?
To make the container run with the host IP run the container with --network host option.
docker run --network host <rest of the command>
Note that if you use '--network host' option, then portmapping '-p' option is not needed.
Read https://docs.docker.com/network/host/ for more information.
Have you checked you've cleaned away any old instances running locally and that you're not trying to access an old instance?
You can wipe out all local docker containers with: docker rm -f $(docker ps -aq)
Once you've got a clean environment you can try spin up the containers again locally and see if you can access the service. I copy/pasted what you have into a clean docker-compose.yaml and ran docker-compose up against the file - it worked and I logged in and was able to view the pg_user table.
If it still fails you can try to find the IP using: netstat -in | grep en0 which will show something like
en0 1500 192.168.1 **192.168.1.163** 15301832 - 9001208 - - -
this shows the external/accessible IP of the container. Try using the address shown (something similar to 192.168.1.163) instead of localhost

Issue when a Python in a docker script connects to a SQL server in a stack

I have a stack in a swarm that works well on its own (at least I think it does...). It has a postgresql working on port 5432 and a web server on port 80. The web server can properly be accessed from the outside.
For unit tests, I run only the database side, in a stack mode:
version: "3"
services:
sql:
image: sql
networks:
- service_network
ports:
- 5432:5432
deploy:
replicas: 1
restart_policy:
condition: on-failure
volumes:
- ./local_storage_sql:/var/lib/postgresql/data
environment:
# provide your credentials here
- POSTGRES_USER=xxxx
- POSTGRES_PASSWORD=xxxx
networks:
service_network:
Then, the unit tests starts by connecting to the db in another simple python container:
FROM python:latest
LABEL version="0.1.0"
LABEL org.sgnn7.name="unittest"
# Make sure we are fully up to date
RUN apt-get update -q && \
apt-get dist-upgrade -y && \
apt-get clean && \
apt-get autoclean
RUN python -m pip install psycopg2-binary
RUN mkdir /testing
COPY ./*.py /testing/
The test script fail when connecting:
conn = connect(dbname=database, user=user, host=host, password=password)
with:
File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
But it only fails when I run it inside the container. From outside, it works like a charm. I also tried setting up an external network and use it (same docker node):
docker run --rm --net service_network -t UnitTest-image py.test /testing
Obviously, I would have expected to be more difficult to access the database from the outside of the network, than from inside, so obviously, I missed something here, but I don't know what...
When you deploy a stack with Compose file, the full name of the network is created by combining the stack name with the base network name. So, let's say you deployed your stack with the name foo like so.
docker stack deploy -c compose-file.yml foo
Then, the full network name will be foo_service_network.
When you run your Python container, you need to connect it to foo_service_network, not service_network.
docker container run --rm --net foo_service_network -t UnitTest-image py.test /testing
You can also customize the network name by specifying the name property in your Compose file (version 3.5 and up).
networks:
service_network:
name: service_network
In which case, you would connect your container to the network with that custom name.
docker container run --rm --net service_network -t UnitTest-image py.test /testing
Edit 1/28: Added Compose file example.
version: "3.7"
services:
sql:
image: sql
networks:
- service_network
ports:
- 5432:5432
deploy:
replicas: 1
restart_policy:
condition: on-failure
volumes:
- ./local_storage_sql:/var/lib/postgresql/data
environment:
# provide your credentials here
- POSTGRES_USER=xxxx
- POSTGRES_PASSWORD=xxxx
networks:
service_network:
name: service_network
attachable: true

docker postgres pgadmin local connection

I have created an ubuntu image with nginx, php and postgres.
I want to connect the postgres database in my current image with pgadmin located on my local machine.
I have tried using docker inspector to try to use the image ip to make a connection with my local pgadmin but without much success. I've also tried configuring some ports on local to make connection work.
It's a valid question don't know why people feel "doesn't seem possible to answer that question".
So, here's how I do what you are trying to do:
Pull postgres image from Docker Hub
docker pull postgres:latest
Run the container using the below command
docker run -p 5432:5432 postgres
Using docker's inspect command find the IP
Use that IP, PORT, Username, and Password to connect in PGADMIN
You can also do a simple telnet like below to confirm if you can access docker postgres container:
telnet IP_ADDRESS 5432
1. Postgres with Docker
docker run \
-p 5432:5432 \
--name container-postgresdb \
-e POSTGRES_PASSWORD=admin \
-d postgres
2. PgAdmin with Docker
docker run \
-p 5050:80 \
-e "PGADMIN_DEFAULT_EMAIL=name#example.com" \
-e "PGADMIN_DEFAULT_PASSWORD=admin" \
-d dpage/pgadmin4
3. Connection string for PgAdmin
Enter PgAdmin on localhost:80. Then add a server with:
name: container-postgresdb
host: host.docker.internal
database: postgres
user: postgres
password: admin
You can also use this to find out the host address โ€” it will be listed as IPAddress in the output โ€”:
docker inspect container-postgresdb \
-f "{{json .NetworkSettings.Networks }}"
This other article might help with more info.
What I have done success on windows 10 running docker for windows 1.12.6(9655), the step is like below:
Pull the latest postgres
docker pull postgres:latest
run the postgres containner:
docker run -d -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password123 --name db-my -p 5432:5432 --restart=always postgres
Then installed the latest version of pgAdmin4 from
pgadmin website
Run pgAdmin 4 create new server, and input as following
Host: 127.0.0.1
Port: 5432
User name: user
password: password123
Then everything is ok, connect to docker postgres instance success.
Alternatively, you could combine Postgres and Pgadmin in one docker-compose file, and login as user pgadmin4#pgadmin.org, pwd: admin. To add the Posgres server, use hostname postgres, port 5432.
version: '3'
services:
postgres:
image: postgres
hostname: postgres
ports:
- "6543:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: TEST_SM
volumes:
- postgres-data:/var/lib/postgresql/data
restart: unless-stopped
pgadmin:
image: dpage/pgadmin4
depends_on:
- postgres
ports:
- "5555:80"
environment:
PGADMIN_DEFAULT_EMAIL: pgadmin4#pgadmin.org
PGADMIN_DEFAULT_PASSWORD: admin
restart: unless-stopped
volumes:
postgres-data:
If you verified that PostgreSQL is running and you can connect there with local copy of PgAdmin...
The answer is simple: use host.docker.internal istead of localhost for the PgAdmin running inside the Docker
In my case I could solve the problem inspecting my postgre image through command
docker inspect CONTAINER_ID | grep IPAddress.
So, I used the docker ip address to config my pgadmin 4 connection and everything was fine. Thanks to #Afshin Ghazi
I included this in the docker yaml file to get the database and pgAdmin:
database:
image: postgres:10.4-alpine
container_name: kafka-nodejs-example-database
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
expose:
- "5432"
ports:
- 8000:5432
volumes:
- ./services/database/schema.sql:/docker-entrypoint-initdb.d/1-schema.sql
- ./services/database/seed.sql:/docker-entrypoint-initdb.d/2-seed.sql
pgadmin:
image: dpage/pgadmin4
ports:
- 5454:5454/tcp
environment:
- PGADMIN_DEFAULT_EMAIL=admin#mydomain.com
- PGADMIN_DEFAULT_PASSWORD=postgres
- PGADMIN_LISTEN_PORT=5454
The postgres username is alphaone and the password is xxxxxxxxxxx.
Do a docker ps to get the container id and then docker inspect <dockerContainerId> | grep IPAddress
eg: docker inspect 2f50fabe8a87 | grep IPAddress
Insert the Ip address into pgAdmin and the database credentials used in docker:
If pgAdmin is intended to be run wihtin same Ubuntu host/guest, then you need to link postgres container, so it could be resolved by a name.
1. Run a postgres container:
docker run --name some-postgres -e POSTGRES_PASSWORD=postgres -d postgres
2. Run pgAdmin container:
docker run -p 80:80 --link some-postgres -e "PGADMIN_DEFAULT_EMAIL=email#domain.com" -e "PGADMIN_DEFAULT_PASSWORD=postgres" -d dpage/pgadmin4
3. Now when adding new server in phAdmin web app, use some-postgres as server name
Note the --link some-postgres when we were bringing up the pgAdmin. This command makes postgres container visible to pgAdmin container.
After facing this issue for two days i was able to resolve that issue.
solution of this problem is already answered by peoples like do inspect
docker inspect CONTAINER_ID
but while running this command i got a-lot of logs like Host Config Config Network Settings etc. so i got confused which IPAddress to add in the pgAdmin connection because i tried 0.0.0.0 and config, host, networkSettings different -2 IPAddress in the logs but finally it works after trying a-lot.
it works with which IP, we have to add that network ip address (which we created to connect the postgres and pgAdmin.)
like in my case when i run :-
docker inspect postgres_container
"NetworkSettings": {
"Bridge": "",
"SandboxID": "sdffsffsfsfsfsf123232e2r3pru3ouoyoyuosyvo8769696796",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"5432/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "5432"
}
]
},
"SandboxKey": "/var/run/docker/231231Ad132",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"postgres": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"postgres",
"0e2j3bn2m42"
],
"NetworkID": "35rhlhl3l53l5hlh3523233k3k4k22l3hk2k4",
"EndpointID":"b3424n43k52o2i4n235k1k4l2l4hj234f14n2",
"Gateway": "192.168.16.1",
"IPAddress": "192.168.16.2",
"IPPrefixLen": 20,
"IPv6Gateway": "",
so we have to add the NetworkSettings -> Network -> Postgres(mine created network) -> IPAddress i.e. "IPAddress": "192.168.16.2".
After adding this ip it will work.
I hope it will help.
This worked for me on Ubuntu 18:
1- Run a postgres container
docker run -d -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password123 --name my-postgres -p 5432:5432 postgres
2- Run a pgAdmin container
docker run --rm -p 5050:5050 thajeztah/pgadmin4
3- Get your local IP (in Ubuntu by ifconfig command)
4- Open localhost:5050 in your browser
5- Click on Servers >> Create >> Server...
6- In General tab, give it a name, for example: docker. In Connection tab, enter these fields:
Host name: The IP from 3
Username: user
Password: password123
7- Click on Save and now everything should work fine.
Note: If this didn't work, try "localhost" for the host name.
In order or find your IP of the container, use following command
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
Referrence: How to get a Docker container's IP address from the host
If you're on a mac and localhost use below as credentials:
version: '3.5'
services:
postgres:
container_name: postgres_container
image: postgres
environment:
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
PGDATA: /data/postgres
volumes:
- postgres:/data/postgres
ports:
- "5432:5432"
networks:
- postgres
restart: unless-stopped
pgadmin:
container_name: pgadmin_container
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4#pgadmin.org}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
PGADMIN_CONFIG_SERVER_MODE: 'False'
volumes:
- pgadmin:/var/lib/pgadmin
ports:
- "${PGADMIN_PORT:-5050}:80"
networks:
- postgres
restart: unless-stopped
networks:
postgres:
driver: bridge
volumes:
postgres:
pgadmin:
Connection:
Hostname/Address: host.docker.internal or 0.0.0.0
Port: 5432
username: postgres
database: postgres
password: changeme
You have to expose the postgres port in the container to you local system. You do this by running your container like this:
docker run -p 5432:5432 <name/id of container>
when connecting with your GUI client or CLI make sure to use the ip-address not localhost even if your ip-address is the localhost ip-address.
docker ps would give you the ip address your postgres container is on.
In my case, I had a PostgreSQL container, so I didn't change my container or create a docker-compose approach, I needed pgadming after few months to had installed PostgreSQL, so this is my approach:
docker inspect my_container_id_postgreSQL
The network assigned to PostgreSQL was:
"Networks": {
"docker_default": {
"IPAddress": "172.18.0.2",
...
}
}
Ran my PGADMIN with --network command.
docker run -p 85:80 --network docker_default -e 'PGADMIN_DEFAULT_EMAIL=user#domain.com' -e 'PGADMIN_DEFAULT_PASSWORD=SuperSecret' -d dpage/pgadmin4
Insert the Ip address into pgAdmin and the database credentials used in docker.
I hope this can be useful for someone.
Regards.
You can create a Docker bridge network to do this too.
$ docker network create pgnet
a0ae44aaf6f806fc37302e4c603b4828c4edb8d487fd9cd90e2fb19ae1d5c65f
$ docker run --detach \
--name pg \
--network pgnet \
--publish 5432:5432 \
--restart always \
--env POSTGRES_PASSWORD=pg123 \
--volume ${PWD}/data:/var/lib/postgresql/data \
postgres:12.1
b60611e43727dabe483c1f08fdf74961b886ce05b432a10a0625bd1b6db87899
$ docker run --detach \
--name pgadm \
--network pgnet \
--publish 8000:80 \
--volume ${PWD}/pgadmin:/var/lib/pgadmin \
--env PGADMIN_DEFAULT_EMAIL=user#domain.com \
--env PGADMIN_DEFAULT_PASSWORD=pgadm123 \
dpage/pgadmin4:4.20
27f9ce1c1c4c383ee1507f4e2d88f6ef33d4fcf5b209a8a03b87519f90d56312
Open http://localhost:8000/
Click Add New Server
Create - Server
Name: db
Hostname/address: pg
Username: postgres
Password: pg123
Save
The Hostname/address used above is the name of the Postgres container given by --name pg
When you start container you have network alias for it. Just use this alias in pgadmin UI.
Like if you have the following docker compose config:
version: "3.5"
services:
postgres:
container_name: postgres-14
image: postgres:14.1
restart: unless-stopped
ports:
- "5432:5432"
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
- POSTGRES_PASSWORD=root
- POSTGRES_USER=postgres
hostname: postgres
pgadmin:
container_name: pgadmin4
image: dpage/pgadmin4
restart: unless-stopped
ports:
- "80:80"
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
- PGADMIN_DEFAULT_EMAIL=user#domain.com
- PGADMIN_DEFAULT_PASSWORD=admin
hostname: pgadmin
You can add server with hostname: postgres
For macOS IPs of postgres and pgadmin4 are different from the ones docker inspect provides.
Type
docker-machine ls
Take a look at the name of the server on the left. It's default by default.
docker-machine ip default will IP you need to use for both, pgadmin4 in browser and for postgres in pgadmin4 settings.
Are you using Window Subsystem LinuxWSL2 to run Docker and PgAdmin?
The steps I suggested is similar to what folks suggested. In my case I am using window environment
Step 1: Open CMD and type ipconfig and hit enter.
Step 2: Check WSL IPv4 Adress
Ethernet adapter vEthernet (WSL):
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : 3bd9::997b:b52a::fe80::65b3%63
IPv4 Address. . . . . . . . . . . : 172.172.172.1 // use the IP as host/address
Subnet Mask . . . . . . . . . . . : 255.255.255.255
Step 3: Open PgAdmin from the browse and create a server
Step 4:
// Here it depends on your desired config mine is the following
Server: postgres
host address: IPv4 Address(step 2)
username: postgress(username for postgress)
password: password(password for postgress)
I spend two days to figure out what was wrong, I hope someone will find it helpful
If local host port 5432 already in use by another psql servers, change it when creating the container and in Pgadmin.
What I have done success on macOS Monterrey running Docker Desktop for macOS(M1):
Pull the latest postgres:
docker pull postgres
Run the postgres container:
docker run -d -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres --name postgres-server -p 5432:5432 --restart=always postgres
Then installed the latest version of pgAdmin 4 (macOS) from pgadmin website
Run pgAdmin 4 create new server, and input as following Host: 127.0.0.1 Port: 5432 User name: postgres password: postgres
pgAdmin 4: Connection postgres-server
Here are the full steps that worked for me
Download and install pgadmin GUI tool
Run docker container: docker-compose up my-db.
From this command logs, note down ipv4 address and port. In my case, it's 0.0.0.0 and 5432.
Open docker-compose.yml file and note down POSTGRES PASSWORD
open pgadmin gui
enter name
In connection tab:
enter that ipv4 address in Hostname/address
enter that port
enter that POSTGRES PASSWORD in password
save. ๐ŸŽŠ
To find the correct ip for your container, execute the following commands:
Check container ID:
docker ps
To check the correct IP of your container:
docker inspect <ID_CONTAINER> | grep "IPAddress"
The configuration of both PostgreSQL and PgAdmin with Docker are simple, if not right, I recommend redoing the configuration from scratch, if your problem is deeper.
Here is a script I developed to solve this problem.
script-sh/install-docker-postgres-and-pgadmin
I did not connect with my container pg (dpage/pgadmin4 image) from browser on 0.0.0.0:9090 .
I ran this command :
docker run --name pg -p 9090:9090 -e PGADMIN_DEFAULT_EMAIL='faizan' -e PGADMIN_DEFAULT_PASSWORD='faizan' -d dpage/pgadmin4
Solution one :
First I tried to inspect the container for IP address
docker inspect pg
I got the container IP address "IPAddress": "172.17.0.3". http://172.17.0.3:9090 did not accessible.
Solution two :
And then I ran command without de-attached mode (-d removed)
docker run --name pg -p 9090:9090 -e PGADMIN_DEFAULT_EMAIL='faizan' -e PGADMIN_DEFAULT_PASSWORD='faizan' dpage/pgadmin4
# Output, it should be running on 9090.
Listening at: http://[::]:80
-p 9090:9090 did not work.
Finally I found the solution :
On some filesystems that do not support extended attributes, it may
not be possible to run pgAdmin without specifying a value for
PGADMIN_LISTEN_PORT that is greater than 1024. In such cases, specify
an alternate port when launching the container by adding the
environment variable, for example:
-e 'PGADMIN_LISTEN_PORT=5050'
Donโ€™t forget to adjust any host-container port mapping accordingly.
Read more about it official doc
I added -e 'PGADMIN_LISTEN_PORT=9090' and worked for me.
You can try both solutions, it will definitely work for you.
I ran this, It worked for me
docker pull dpage/pgadmin4
docker run -p 9000:80 -e 'PGADMIN_DEFAULT_EMAIL=test#gmail.com' -e 'PGADMIN_DEFAULT_PASSWORD=root' -d dpage/pgadmin4
The solution I tried and worked for me, was to create a docker compose file where I included postgress and pgadmin as services. For more details: Connecting pgadmin to postgres in docker
Tested on Mac
pgAdmin-4: version 6.12
I tried several answers here and in other places but nothing worked for me.
Here is the problem I had and the solution.
I had a docker postgres running my machine and need to connect this server in pgAdmin.
All I need to do was to check the docker information and fill the server configs based on that in pgAdmin.
You can do this by opening your docker and going to dashboard and then selecting the postgres image you're using. There is a tab called Inspect click on that. Here you can get all the information about that postgres container.
Now open the pgAdmin and resister a server by right clicking on the servers -> Register -> Server.
choose a name for the server and click Connection tab.
Here we need to fill the data like host name/address, IP, ports and etc.
In docker Inspect tab, there is Ports section that you can get this data from, something like this:
So your host address based on this picture is 172.0.0.1 and port is 5873.
Other info like database, user and password is also available in Environment section in docker Inspect tab.
Now fill the other information click save in pgAdmin and it should work.
Go to your container terminal on Docker Desktop and type hostname -I in case is linux to get the ip assigned to this machine, then go to your pgAdmin an try it out. #Rigoxls