Running Postgres Locally with Docker
Step 1 - Install Docker
If you haven’t already, visit docker.com and download the desktop application for your OS.
The beauty of Docker is that it allows you to run software without dealing with a ton of OS or dependency headaches!
Step 2 - Run a PostgreSQL docker container
The following command will download and run a docker image containing PostgreSQL 13.1 locally.
docker container run --name postgresdb -p 5432:5432 -v pgdata -e POSTGRES_PASSWORD='mypass12345' postgres:13.1
Let’s break it down:
docker container run- This is the command to run a new docker container. You would use
docker startto restart a container.
--name postgresdb- Given the container a name. Unless you give the container a name, you’ll end up with some randomly generated letters that are impossible to remember.
-p 5432:5432- This is the line that makes our database accessible to the outside world - it maps port
5432from the PostgreSQL image to the outside of the container. You can access PostgreSQL by pointing PSQL at this port, if you want. We’re not going to do that, but I think its good to mention.
-v pgdata- This line creates a volume called
pgdata. If we didn’t create a volume, we would lose all data in our database every time we shut down docker.
-e POSTGRES_PASSWORD='mypass12345'- This line passes an environment variable to set the password needed to log in to the database. PostgreSQL will refuse to start if you don’t pass this environment variable!
postgres13:1- Here we specify the image (and tag, after the colon) we want to run. You can see the official PostgreSQL Dockerhub image here.
Step 3 - Connect to PostgreSQL
At this point, if you have PSQL on your computer, you can connect to the database by using PSQL.
We’re going to go inside the Docker container first - it makes it so we don’t have to install anything else on our computer.
Open another tab in your command line client and run:
docker exec -it postgresdb psql -U postgres
Let’s break that one down:
docker exec -it postgresdb- The
docker exec -itpart specifies that we want to get inside of a docker image.
postgresdbis the name of the container we want to get into.
psql -U postgres- PSQL is an official PostgreSQL command line utility that is automatically installed along with PostgreSQL in the container. Running PSQL connects you to a database.
-U postgresspecifies the user we want to connect as.
postgresis the default username when you start a new PostgreSQL database.
Step 4 - Do some data stuff!
That’s it! Hope this helps you. Click here to check out the next video where we will spin up a PostgreSQL database in the cloud on AWS!