Docker is a platform that helps in running the application in the form of a docker container. We can easily set up theย PostgreSQLย database for local development with the help of docker. In this article, we will learn to set up a local PostgreSQL database with the help of docker.
Table of Contents
Running the PostgreSQL container
We can run the PostgreSQL docker container with the help of the below docker command.
docker run --name my-postgres -p 5432:5432 -e POSTGRES_PASSWORD=password -d postgres
- Here, we are using the latest version of theย postgresย docker image. The docker pulls the the PostgreSQL docker image from the docker hub if it’s not already available in the local system.
- We have also specified a name called my-postgres to our container with the help of the flag –name.
- We are exposing the default port 5432 of the PostgreSQL database, so that external services can connect to the database.
- The password for the database is set with the help of POSTGRES_PASSWORD environment variable.
We can verify the docker image pulled from the docker hub with the help of below command.
docker images

Once the container is up and running, we can verify the container with the help of below command.
docker container ps -a

Entering into the PostgreSQL docker container shell
We can enter into the PostgreSQL docker container shell with the below command.
docker exec -it my-postgres bash
We can then run the SQL commands as shown below. Here, we are creating a test_db database.
CREATE DATABASE test_db;

To exit from the psql shell, we can use below command.
exit
Now, switch to the newly createdย test_dbย database with the help of the below command.
psql -U postgres -d test_db

Now we can run the SQL scripts inside the psql shell.
Conclusion
In this article, we learned how simple it is to set up a PostgreSQL database in the local system.
Discover more from ASB Notebook
Subscribe to get the latest posts sent to your email.