๐Ÿš€ Setup: PostgreSQL & Docker

Deploy a PostgreSQL database in minutes with Docker

๐Ÿš€ Setup: PostgreSQL & Docker

Pre-requisites: Docker installed on your machine.

โœจ Introduction

Running PostgreSQL on Docker is a game-changer for both beginners and experienced developers. It's a cutting-edge solution that brings convenience, flexibility, security and efficiency to your database setup.

  1. Easy Setup and Portability: Docker allows you to effortlessly set up PostgreSQL with just a few simple commands. Say goodbye to complex installations and compatibility issues! With Docker, your PostgreSQL environment becomes portable, meaning you can run it consistently across different machines and environments.

  2. Isolation and Security: Docker containers provide an isolated environment for PostgreSQL, ensuring that your database operates independently of the host system as it enhances security, preventing interference or unintended changes from other applications or processes.

  3. Version Management Made Simple: Have multiple PostgreSQL projects with different versions? You can have multiple PostgreSQL instances running simultaneously, each with its specific version, without any conflicts.

  4. Scalability at Your Fingertips: As your database needs grow, Docker effortlessly scales up your PostgreSQL setup. You can easily replicate containers, distribute the load, and manage resources, ensuring smooth and efficient database performance.

  5. Data Persistence with Volumes: Docker volumes enable data persistence, so your precious PostgreSQL data remains intact even if containers are stopped or updated. This ensures your valuable information is always available when you need it.


๐Ÿš€ Postgres and Docker Setup

Start the Docker installed on your machine, and follow the steps below.

๐Ÿงฐ Pull the image

To run the Postgres database, we first need to pull the postgres image on our docker. Run this command in your terminal:

docker pull postgres

This command will download the postgres image on your docker.

๐Ÿ Start the Postgres Container

Now let's write a command that we need to run the image to create a container that will start the Postgres Database Server.

docker run --name test-postgres \
-e "POSTGRES_USER=john" \
-e "POSTGRES_PASSWORD=mysecretpassword" \
-e "POSTGRES_DB=mydb" \
-p 5432:5432 -d \
-v postgres_volume:/var/lib/postgresql/data \
postgres
  • --name is the flag that is used to set a name for the container. Here the name is test-postgres.

  • -e is used to pass the env variables. Here the env variables are POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB.

  • -p 5432:5432 means mapping the Docker Host port to Container Port, and here both the ports are the same.

  • -d means running the container in detached mode.

  • postgres is the image name.

  • -v postgres_volume:/var/lib/postgres/data will be explained in the next section

๐Ÿ—„๏ธ Docker Volume

Volumes are managed by Docker and are essential for preserving data even if containers are stopped, restarted, or removed.

-v is used to create a volume in the path /var/lib/postgresql/data, which is the default path, will contain the data required for the containers.

postgres_volume is the named volume present in that directory.

There are also anonymous volumes.

An anonymous volume in Docker is a volume that is created without a specified name. When you create an anonymous volume, Docker assigns it a random name that is guaranteed to be unique within the scope of the host.

The name of an anonymous volume is a long string of letters and numbers, such as 83a3275e889506f3e8ff12cd50f7d5b501c1ace95672334597f9a071df439493

You can view the list of volumes, including anonymous volumes, on your host by running the command docker volume ls.

๐Ÿ”— Connect to PostgreSQL using psql

To connect to the PostgreSQL container, use the following command:

docker exec -it test-postgres psql -U john -d mydb

Let's look at the breakdown of the command:

  • docker exec: This command is used to execute a command in a running container.

  • -it flag is used when running the docker exec command. It is a combination of two separate flags: -i and -t, which serve different purposes.

    • -i (or --interactive): It enables you to interact with the container's process by providing input through the command line.

    • -t (or --tty): This flag allocates a pseudo-TTY (Teletypewriter) for the container. It allows you to see the output of the command and provides a terminal-like interface, making the interaction with the container more user-friendly.

  • test-postgres: This specifies the name of the container in which the command will be executed.

  • psql: This is the command that will be executed inside the container. It stands for PostgreSQL interactive terminal.

  • -U john: The -U flag stands for user and specifies the name of the user to connect as. In this case, it is connecting as user john.

  • -d mydb: The -d flag is used to state the database you are going to use.

After the running the above command, the psql terminal will open. Now you can interact with your postgres database by running your SQL commands.


๐Ÿ› ๏ธ Basic psql commands

Source

Here are some basic commands to help you interact with your PostgreSQL database using psql:

  • To execute an SQL query, simply type it at the prompt followed by a semicolon (;), and hit enter. For example:

      mydb=> SELECT * FROM mytable;
    

    mydb is the name of the database.

  • To quit psql, type \q and hit enter:

      mydb=> \q
    
  • To list all databases in your PostgreSQL server, use the \l command:

      mydb=> \l
    
  • To switch to another database, use the \c command followed by the database name:

      mydb=> \c anotherdb
    
  • To list all tables in the current database, use the \dt command:

      mydb=> \dt
    
  • To get information about a specific table, use the \d command followed by the table name:

      mydb=> \d mytable
    

๐Ÿ’ก Shortcut: Docker-Compose

Create a yaml file 'docker-compose.yml' and write down this code for postgres and volume setup.

version: '3.9'

services:

  postgres:
    image: postgres:latest
    container_name: test-postgres
    environment:
      POSTGRES_USER: john
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: mydb
    ports:
      - "5432:5432"

    volumes:
      - postgres_volume:/var/lib/postgresql/data

volumes:
  postgres_volume:
    driver: local

Breakdown of the docker-compose yml file

  • version: '3.9': This specifies the version of the Docker Compose file syntax being used. In this case, version 3.9 is used.

  • services: This section defines the services (containers) that will be created and managed by Docker Compose.

  • postgres: This is the service name for the postgres container.

  • image: postgres:latest: This line specifies the Docker image to be used for the PostgreSQL service.

  • container_name: test-postgres : This option sets the name of the container to "test-postgres".

  • environment : This section allows you to set environment variables within the postgres container. The specified environment variables are POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB.

  • ports: This option maps the host machine's port 5432 to the container's port 5432, allowing access to the postgres service inside the container using port 5432 on your host machine.

    Here the host machine is Docker Host. To know more, follow this guide.

  • volumes: This section defines the volumes to be used by the containers.

  • - postgres_volume:/var/lib/postgresql/data: This line creates a named volume called "postgres_volume" and mounts it to the /var/lib/postgresql/data directory inside the PostgreSQL container. This allows the PostgreSQL data to be persisted even if the container is removed.

  • volumes: This section defines the named volume "postgres_volume".

  • driver: local : This line specifies the volume driver to be used for the named volume. In this case, it uses the local driver, which means it will be managed by Docker on the local filesystem.

Then run this command:

docker-compose up -d

The above command will create a container from the postgres image and also volume for this container.


The End... :)

Comment about the next concept or topic you would like to know.

โž• Follow for more such content.

๐Ÿ‘ Like if you found this article useful :)

๐Ÿ’ฌ Feedback would be appreciated.

๐Ÿ”— Share if possible :D

Peace โœŒ๏ธ

Did you find this article valuable?

Support Mayukh's Blog by becoming a sponsor. Any amount is appreciated!

ย