Super Easy - Postgres Database on Docker
Quick and easy way to get Postgres up and running on Docker
Setting up a Postgres database on your computer can be a pain in the backside. With weird setup methods and installations can sometimes lead you to feeling demoralised.
If only there was a quick an easy way to get up and running.
Fortunately there is, thanks to Docker.
In this article I am going to show you how I setup a Postgres database using Docker. So treat this article as more of a cheat sheet.
TLDR
docker pull postgres:alpine
docker run --name postgres-container -e POSTGRES_PASSWORD=password -d -p 5432:5432 postgres:alpine
docker exec -it postgres-container bash
psql -U postgres
CREATE DATABASE mydb;
CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypass';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
ALTER USER myuser WITH SUPERUSER;
Part 1 — Docker Setup
Assuming you have Docker already installed.
In your command line run the command
docker pull postgres:alpine
If you want to check what images are currently installed
docker images
Then we want to setup the Docker container to host our Postgres database.
docker run --name <name_of_container> -e POSTGRES_PASSWORD=<your_password> -d -p 5432:5432 postgres:alpine
Anything that you see inside of the arrow bracket
<>
is for you to decide.
To see the containers that you have you can run
docker ps
. You should see your new container running based on what you put for<name_of_container>
Part 2 — Database Setup
Now that we have the container spinning we can jump into it by running
docker exec -it <name_of_container> bash
Once you’re in the container you have to make another leap to access the Postgres shell. To do that run
psql -U postgres
You can now start entering Postgres commands. So let’s use one to create a database. Run
CREATE DATABASE <name_of_database>;
The database also needs a user.
CREATE USER <username> WITH ENCRYPTED PASSWORD '<password>';
Finally we can link our new user to the database with the correct permissions.
GRANT ALL PRIVILEGES ON DATABASE <name_of_database> TO <username>;
ALTER USER <username> WITH SUPERUSER;
Congratulations
That’s is we’re now done with setting up a Postgres database. If you had any issues be sure to drop a comment or contact me on Twitter.