Running The PostgreSQL On Docker

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
docker image postgres

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

docker container ps -a
docker postgres container

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;
docker postgres shell

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

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.

Running The PostgreSQL On Docker

Leave a Reply

Scroll to top

Discover more from ASB Notebook

Subscribe now to keep reading and get access to the full archive.

Continue reading