'Can't connect to PostgreSQL docker image (with a forwarded port)

I created my docker image with the following command -

sudo docker run -d --name pg1 -e POSTGRES_PASSWORD=pass -p 5431:5432 postgres

I tried connecting using psql -

psql -h 127.0.0.1 -p 5431

and after a while it returns -

psql: error: could not connect to server: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.

The output to docker ps -

CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                                                                                        NAMES
7544edb21da1        postgres                "docker-entrypoint.s…"   4 minutes ago       Up 4 minutes        0.0.0.0:5431->5432/tcp            

                                                       pg1

The output to docker inspect -

[
    {
        "Id": "7544edb21da1f0eba57fe6e010ca95f763dc8224f347c096aa2c8409d21a9368",
        "Created": "2020-10-18T12:27:00.829493238Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "postgres"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 248693,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-10-18T12:27:01.372006934Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:c96f8b6bc0d9f0277f118cf485a8c302e32cfe05e7d65f6e9a4c106679439d5e",
        "ResolvConfPath": "/var/lib/docker/containers/7544edb21da1f0eba57fe6e010ca95f763dc8224f347c096aa2c8409d21a9368/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/7544edb21da1f0eba57fe6e010ca95f763dc8224f347c096aa2c8409d21a9368/hostname",
        "HostsPath": "/var/lib/docker/containers/7544edb21da1f0eba57fe6e010ca95f763dc8224f347c096aa2c8409d21a9368/hosts",
        "LogPath": "/var/lib/docker/containers/7544edb21da1f0eba57fe6e010ca95f763dc8224f347c096aa2c8409d21a9368/7544edb21da1f0eba57fe6e010ca95f763dc8224f347c096aa2c8409d21a9368-json.log",
        "Name": "/pg1",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "5432/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "5431"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/40586201c29ccea2586cba608e6fb64dffd5ece30d89cc1087ee2e43a7a5b746-init/diff:/var/lib/docker/overlay2/5cb4a9544fb587c2fb21b8934c88a5c20d468d417efbb9b548c12c3da0dea207/diff:/var/lib/docker/overlay2/7bf8dd38278f17616c2b8ad798787db97f2f899175a613deb3f0cdff243793e3/diff:/var/lib/docker/overlay2/cd3006fdad38af40b2bceb3b1e71e70cdf341faad0f1fc035d9e9fbef6dd57b8/diff:/var/lib/docker/overlay2/29c9aceb670eb25359c1c0b2880e781137ef8e64bc3b54f2a3b7838f1e082f3d/diff:/var/lib/docker/overlay2/02cc88690586248e33d42a8b69af97d65b53e9777daf31f7fde20146fe632aad/diff:/var/lib/docker/overlay2/ac82aefa647c8172c2f0a32024bcfdb26216503779a0874ce28de6844ac5fcfb/diff:/var/lib/docker/overlay2/ead4901bcad157e446a77e1ffe8e11bd16e3bf07c5107f297144066f95f40bfb/diff:/var/lib/docker/overlay2/ebc2bb6cb6811988a05818275f133045e61ed50660045b4a912d5fdc1b6fc651/diff:/var/lib/docker/overlay2/545fef5599babc61f384e20617a705d76cfbffd0abc93a1f0dd9a0d0f4ce3ab2/diff:/var/lib/docker/overlay2/a096d23ddb6f5971d55f3dd5a74cecb6461bed20b03d0f568cc21009d1f5d7e7/diff:/var/lib/docker/overlay2/8add50b416d00917dbee83a176f67dee2e974cc0e5741810181cd74170e0928d/diff:/var/lib/docker/overlay2/594f6265418c37118caa08de40a1d4f1cbbf60fc3c557575c67b545b9454a3fc/diff:/var/lib/docker/overlay2/a4e8ba0efb607e5d8af671039b5ecb9536b6dc48d3c525ce034de22ecd76c331/diff:/var/lib/docker/overlay2/07b1f48b8e0462fb5359411156635b73321b9555bf23cff2036dfe0d69ea1ea5/diff",
                "MergedDir": "/var/lib/docker/overlay2/40586201c29ccea2586cba608e6fb64dffd5ece30d89cc1087ee2e43a7a5b746/merged",
                "UpperDir": "/var/lib/docker/overlay2/40586201c29ccea2586cba608e6fb64dffd5ece30d89cc1087ee2e43a7a5b746/diff",
                "WorkDir": "/var/lib/docker/overlay2/40586201c29ccea2586cba608e6fb64dffd5ece30d89cc1087ee2e43a7a5b746/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "8f60dae263f54c3c9e38a37b1c86512dffa254f77830de8d5a5e260c94e69319",
                "Source": "/var/lib/docker/volumes/8f60dae263f54c3c9e38a37b1c86512dffa254f77830de8d5a5e260c94e69319/_data",
                "Destination": "/var/lib/postgresql/data",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "7544edb21da1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "5432/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "POSTGRES_PASSWORD=pass",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/13/bin",
                "GOSU_VERSION=1.12",
                "LANG=en_US.utf8",
                "PG_MAJOR=13",
                "PG_VERSION=13.0-1.pgdg100+1",
                "PGDATA=/var/lib/postgresql/data"
            ],
            "Cmd": [
                "postgres"
            ],
            "Image": "postgres",
            "Volumes": {
                "/var/lib/postgresql/data": {}
            },
            "WorkingDir": "",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {},
            "StopSignal": "SIGINT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "15915142f795248c698fd8dacafc8eadd6dd940a46ff21a00c31a8b5cb6bbb10",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "5432/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "5431"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/15915142f795",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "e76fa7145141ec7ff5a088135f096ab8bbdbdf6fe06fd69e229fc152a4dee779",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.4",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:04",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "5e91a000cbb899564472694a4bbddb4b3e4009c6944d0c801d1473ef71d61fe6",
                    "EndpointID": "e76fa7145141ec7ff5a088135f096ab8bbdbdf6fe06fd69e229fc152a4dee779",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:04",
                    "DriverOpts": null
                }
            }
        }
    }
]

Connecting to the SQL server inside the container works. But outside it doesn't work.
What can be done here? What am I missing?



Solution 1:[1]

First of all, you didn't create a docker image, you created a docker container named: pg1 from the official image postgres,

Based on your docker inspect the output, I think it will work on host 172.17.0.4 and port 5432. So try below command -

psql -h 172.17.0.4 -p 5432

With pgadmin(if you set it up),

 host: 172.17.0.4
 port: 5432
 username: postgres
 password: pass

Also, this will help you why the current psql -h 127.0.0.1 -p 5431 way is not working, "psql: could not connect to server: Connection refused" Error when connecting to remote database

Solution 2:[2]

Had the same issue. Restarting docker helped, in my case it was:

sudo service docker restart 

Spent some time on this, may this save someone else's time )

Solution 3:[3]

For me the issue was caused by having my VPN client running. Worked again when disconnecting it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Suor
Solution 3 apelsimon