DEV Community

theBridge2
theBridge2

Posted on • Updated on

Run PostgreSQL in docker

Overview
Image description

1) Setting up

Get docker
https://www.docker.com/get-docker

Go to terminal to prove the install succeeded.

docker --help
Enter fullscreen mode Exit fullscreen mode

Get postgres image to use in docker.
https://hub.docker.com/_/postgres

docker pull postgres:alpine
Enter fullscreen mode Exit fullscreen mode

This is the smallest postgres install image to use for testing.

2) Start docker postgres container

docker run --name any_image_name -e POSTGRES_PASSWORD=mypassword -d -p 5432:5432 postgres
Enter fullscreen mode Exit fullscreen mode

-> -e creates an environment variable
-> -p 5432:5432 exposes port 5432 to external to the container

3) Test docker image with psql

Link to my PostgreSQL cheat sheet

Useful reference: https://stackoverflow.com/questions/37694987/connecting-to-postgresql-in-a-docker-container-from-outside

docker ps     # Get container id
docker exec -it container_id bash  #Connect to docker container using bash prompt
Enter fullscreen mode Exit fullscreen mode

Inside of docker container bash prompt

psql -U postgres # connect to postgres
Enter fullscreen mode Exit fullscreen mode

Inside of a successful postgres connection with psql in docker container

CREATE DATABASE test;  #Create database
\q  # Quit
Control+C. #Exit out of bash shell inside docker container
Enter fullscreen mode Exit fullscreen mode

Test from outside docker container:

psql -h localhost -p 5432 -U postgres
\list  # see the database you created.
Enter fullscreen mode Exit fullscreen mode

Troubleshooting

This section is mac os/linux specific. For windows, you will need to find the corresponding troubleshooting commands.

Port issues

IF port error - debug ports in use with this command

sudo lsof -i -P | grep LISTEN | grep :5432   
Enter fullscreen mode Exit fullscreen mode

If you find anything like postgres or anything else listening on the port, run

sudo kill process_id
Enter fullscreen mode Exit fullscreen mode

where process id is the second column of what was returned from the above lsof command.

Check to see if other docker containers are running trying to use the same port

docker ps -a  # get list of all containers
docker stop container_id
docker rm container_id
Enter fullscreen mode Exit fullscreen mode

Other instances of postgres running

Check services running

brew services list
Enter fullscreen mode Exit fullscreen mode

If anything running with brew you need to kill, run

brew services stop service_name
Enter fullscreen mode Exit fullscreen mode

4) Connect with python, node JS etc.

Now that you proved you can connect to your docker containerized postgres instance, you can use your normal approaches to connect to postgres not inside a docker container.

Top comments (0)