How to run Postgres in Docker

brokenrice
2 min readJun 17, 2024

--

Quick guide to get started to use postgreSQL

1. download docker image

docker pull postgres

2. Create a docker container from the image and run it locally

docker run -p 5432:5432 --name local-postgres -e POSTGRES_PASSWORD=myPassword -d postgres

Here’s the explanation of the parameters:

  • -p 5432:5432 : map the container port 5432 to the host port 5432. This is important if you want to access the DB server from the host. In my case I have pgAdmin installed directly on my computer, so I wanted to use it to manage the DB in docker instead of spinning up another docker container for pgAdmin
  • --name : the name of the container
  • -e : the environment variables required to run the image.
  • -d : detach mode, i.e run container in background

3. Connect to the postgres server using pgAdmin

Noted that we have mapped the container port to the host port, and we will connect to the postgres container directly from the host, so the address would be localhost:5432 when configuring pgAdmin. If you’re using pgAdmin in another docker container, then the address would be `host.docker.internal`.

If everything is configured properly, then you should be able to see the DB in the pgAdmin dashboard

4.Troubleshooting

  1. Error Fatal: role “postgress" does not exist when connecting to database

The postgress docker image comes with pre-setup role “postgres”, so if you still encounter that error, it’s likely that you have something else running on the same port. On MacOS, you can run lsof -n -i:5432 | grep LISTEN to check. There should be only 1 process running on the port.

To fix the error, you can try close other application/process that occupy posgres port, or re-map the postgres container to different port, for example, below command will map the postgres container port 5432 to the port 5433 of the host machine

docker run -p 5433:5432 --name local-postgres -e POSTGRES_PASSWORD=myPassword -d postgres

--

--

brokenrice
brokenrice

Written by brokenrice

A developer who loves broken rices

No responses yet