If you're learning how to use postgresql with Docker from tutorials online, you might have trouble connecting to postgresql in your container, perhaps especially if you're on Windows. This might help.
I'm on Windows 10. Your mileage may vary if you're on other systems or if your system configurations are somehow different.
A lot, a lot of tutorials tell us to do this first:
docker run --rm --name con1 -e POSTGRES_PASSWORD=1234 -p 5432:5432 -d postgres
Essentially, this runs a Docker container from a postgres:alpine image. If like me you already have postgresql running on port 5432 of your machine, this will fail immediately with:
"docker: Error response from daemon: driver failed programming external connectivity on endpoint con1 (7a026b9b6df0fbb221f4c23b538d8d68bc90476a66abfa6a05ae6229ac083646): Error starting userland proxy: mkdir /port/tcp:0.0.0.0:5432:tcp:172.17.0.2:5432: input/output error."
However, you might get this or other similar errors because of a different reason. To confirm it a little bit more, check if postgresql is really using port 5432 on your machine by first running:
netstat -aon | findstr 5432. This gets you all processes using the port. You should see something like this:
TCP 0.0.0.0:5432 0.0.0.0:0 LISTENING 10732
TCP [::]:5432 [::]:0 LISTENING 10732
The last number is the process identification number (PID). It's 10732 here but it will likely be different on your system. We can use it to find the program in question with:
tasklist /fi "pid eq 10732". You'll see something like this:
Image Name PID Session Name Session# Mem Usage
========== ============== ======= ==========
postgres.exe 10732 Services 0 16,676 K
In my case, it's postgresql!
If yours is the same, you'll need to map an unused port on your machine to the container. I usually use port 5431 on my machine these days.
After running a container successfully, tutorials usually tell you to connect to postgresql inside your container with this command:
psql -h 0.0.0.0 -U postgres. You might get:
"psql: could not connect to server: Cannot assign requested address (0x00002741/10049)
Is the server running on host "0.0.0.0" and accepting
TCP/IP connections on port 5432?"
Check this solution out for a more rounded out idea of why this command might fail.
Instead, do this:
psql -h 127.0.0.1 -p 5431 -U postgres. We can replace
localhost if we like. It should work now. The
-h flag is for the host, in this case your machine. And
-p is for the port, which is 5431 for me as mentioned before.
These couple of gotchas might not be why you can't connect to postgres in your container. Maybe your postgres configuration needs to be changed. Here's one solution out of several on Stack Overflow.