Run PostgreSQL in docker

Run PostgreSQL in docker

Overview

1) Setting up

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

Go to terminal to prove the install succeeded.

docker –help

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

docker pull postgres:alpine

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

-> -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

Inside of docker container bash prompt

psql -U postgres # connect to postgres

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

Test from outside docker container:

psql -h localhost -p 5432 -U postgres
list # see the database you created.

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

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

sudo kill process_id

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

Other instances of postgres running

Check services running

brew services list

If anything running with brew you need to kill, run

brew services stop service_name

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 a postgres image not inside the container.

Leave a Reply

Your email address will not be published. Required fields are marked *