PostgreSQL: How to use Docker Image to start a PostgreSQL DB server?
To start PostgreSQL DB server by docker image is one cool way to use PostgreSQL. This article is to tell how to do it in details.

Run the docker image of postgres
> docker run --name db-data-analysis -e POSTGRES_PASSWORD=0ELhge5Y57&K -d postgres
The command above is to create a new container named as db-data-analysis
with the docker image postgres
and run the container in background (-d) with environment variable POSTGRES_PASSWORD
whose value is set as 0ELhge5Y57&K
. The command will exit immediately by print the container ID.
0bc90d4a33a405e08823d6f3729972ff7e07c7a7a519e1ddabce26079f1266f4
Connect to the PostgreSQL DB server started by docker container
To connect to the PostgreSQL DB server, we need to know the IP address of the container and the Port number of the DB server. This can be done by the command below:
docker container inspect 0bc90d4a33a405e08823d6f3729972ff7e07c7a7a519e1ddabce26079f1266f4
and in the output we can find below information (the concrete value might be differe):
"NetworkSettings": {
"Bridge": "",
"SandboxID": "42047eac649c199145c5356863fd233b8c3acc0f28a26a255f36fc45d37c7211",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"5432/tcp": null
},
"SandboxKey": "/var/run/docker/netns/42047eac649c",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "73830c5720e832feba1fffdf73868022367a435ac590b019accc6f4d77f74909",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "6fbb3235e4a4cd4bf1fe20dddfbab41c09c52f02527d5e7cc4c2cd50caa05939",
"EndpointID": "73830c5720e832feba1fffdf73868022367a435ac590b019accc6f4d77f74909",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
}
Then, we can use the below command(in host) to connect to the PostgreSQL DB server:
psql -h 172.17.0.2 -p 5432 -U postgres
📓 The command psql
is provided by postgresql client program. If it’s not available, then do installation firstly, e.g. sudo yum install postgresql15.x86_64
`.
It will create the prompt to ask the password:
Password for user postgres:
Use the password we set by the environment variable POSTGRES_PASSWORD
above, and we are in:
psql (12.13 (Ubuntu 12.13-0ubuntu0.20.04.1), server 15.2 (Debian 15.2-1.pgdg110+1))
WARNING: psql major version 12, server major version 15.
Some psql features might not work.
Type "help" for help.
postgres=#
Refer to Postgres official docker image web page for more information. Thanks for reading and happy coding!