How to Install PostgreSQL on Docker with Docker Compose

How to Install PostgreSQL on Docker with Docker Compose

PostgreSQL is a powerful, open-source relational database system that is widely used for its reliability and advanced features. Docker is a popular containerization platform that simplifies the deployment of applications by packaging them with their dependencies. Docker Compose is a tool that helps define and run multi-container Docker applications. This guide will walk you through the process of installing PostgreSQL on Docker using Docker Compose. The instructions are clear and easy to follow, even if you are new to Docker or PostgreSQL.


Prerequisites

Before we begin, make sure you have the following prerequisites installed on your system:

  1. Docker: Docker is required to create and manage containers. You can download Docker from the official Docker website and follow the installation instructions for your operating system.
  2. Docker Compose: Docker Compose is used to define and manage multi-container Docker applications. You can install Docker Compose by following the instructions on the Docker Compose documentation.
  3. Basic command-line knowledge: Familiarity with the command line will help you execute the commands needed for this setup.

Once you have these prerequisites in place, you’re ready to proceed.


Step 1: Create a Project Directory

The first step is to create a directory on your local machine that will hold your PostgreSQL project files.

mkdir postgres-docker
cd postgres-docker

 

This directory will contain the Docker Compose configuration file and other necessary files.


Step 2: Create a docker-compose.yml File

Next, you need to create a docker-compose.yml file. This file will define the services, networks, and volumes that Docker Compose will use to set up PostgreSQL.

Create a new file named docker-compose.yml in your project directory:

touch docker-compose.yml

 

Open the file with a text editor and add the following configuration:

version: '3.8'

services:
  db:
    image: postgres:latest
    container_name: postgres
    restart: always
    environment:
      POSTGRES_USER: exampleuser
      POSTGRES_PASSWORD: examplepass
      POSTGRES_DB: exampledb
    volumes:
      - db_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

volumes:
  db_data:

 

This configuration file defines the following:

  • PostgreSQL Service: It uses the official PostgreSQL Docker image. The service is named db, and the container is named postgres. The container is configured to restart automatically if it stops. The environment section sets up the PostgreSQL database, user, and password. The database files are stored in a Docker volume for data persistence.
  • Volumes: Docker volumes are used for persistent storage. In this case, the db_data volume stores the PostgreSQL data files.
  • Ports: The container’s port 5432 (default PostgreSQL port) is mapped to port 5432 on your local machine.

Step 3: Start the Docker Container

With the docker-compose.yml file configured, you can now start the PostgreSQL container.

Run the following command in your project directory:

docker-compose up -d

 

The -d flag runs the container in detached mode, which means it will run in the background. Docker will download the necessary PostgreSQL image and start the container.

You can check the status of your container with:

docker-compose ps

 

This command lists all running containers and their status.


Step 4: Accessing PostgreSQL

Once the container is running, you can access PostgreSQL using a PostgreSQL client like psql or any graphical database management tool.

Using psql

If you have psql installed on your local machine, you can connect to your PostgreSQL database using the following command:

psql -h localhost -U exampleuser -d exampledb

 

You will be prompted to enter the password you set in the docker-compose.yml file (examplepass).

Using a GUI Tool

You can also use a graphical tool like pgAdmin, DBeaver, or TablePlus to connect to your PostgreSQL database. Use localhost as the host, 5432 as the port, exampleuser as the username, and examplepass as the password.


Step 5: Managing Your Docker Containers

Docker Compose provides several commands to manage your containers. Here are some useful commands:

  • Stopping Containers: To stop your container without removing it, use the following command:bashCopy codedocker-compose stop
  • Starting Containers: If your container is stopped, you can start it again with:bashCopy codedocker-compose start
  • Restarting Containers: To restart your container, use:bashCopy codedocker-compose restart
  • Removing Containers: If you want to remove your container along with its associated network, use:bashCopy codedocker-compose down This command removes the container but keeps the persistent data in the volume intact. To remove the volume as well, add the -v flag:bashCopy codedocker-compose down -v

Step 6: Customizing Your PostgreSQL Setup

You can customize your PostgreSQL installation by modifying the docker-compose.yml file or adding additional configurations.

Customizing Environment Variables

The PostgreSQL Docker image supports several environment variables that allow you to customize the database setup. For example:

  • POSTGRES_INITDB_ARGS: Specifies additional arguments to pass to the database initialization.
  • POSTGRES_HOST_AUTH_METHOD: Configures the authentication method for PostgreSQL.

You can add these variables under the environment section in your docker-compose.yml file.

Creating a Custom Dockerfile

For advanced users, creating a custom Dockerfile can help you add additional configurations to your PostgreSQL container. For example, you might want to include custom configuration files or install additional extensions.

Here’s an example of a Dockerfile that extends the official PostgreSQL image:

FROM postgres:latest

# Copy custom configuration files
COPY custom-config.conf /etc/postgresql/conf.d/

# Install additional extensions
RUN apt-get update && apt-get install -y postgresql-contrib

 

After creating this Dockerfile, build your custom image with:

docker build -t custom-postgres .

 

Then update your docker-compose.yml to use the custom-postgres image instead of postgres:latest.


Step 7: Backing Up and Restoring Your PostgreSQL Data

Backing up your PostgreSQL data is crucial, especially when using containers. Since PostgreSQL data is stored in Docker volumes, you need to back up these volumes.

Backing Up Volumes

To back up your Docker volume, you can use the docker run command to create a backup tarball:

docker run --rm --volumes-from postgres -v $(pwd):/backup ubuntu tar czvf /backup/db_data_backup.tar.gz /var/lib/postgresql/data

 

This command creates a compressed tar file containing your PostgreSQL data, which you can store securely.

Restoring from Backup

To restore your volume from a backup, first ensure the container is stopped, then use the following command:

docker run --rm --volumes-from postgres -v $(pwd):/backup ubuntu bash -c "cd /var/lib/postgresql/data && tar xzvf /backup/db_data_backup.tar.gz --strip 1"

 

This command extracts the backup file into the appropriate directory within the container.


Step 8: Scaling Your PostgreSQL Setup

Docker Compose makes it easy to scale your services by simply defining more containers. However, scaling a PostgreSQL service involves some considerations regarding data consistency and replication.

Scaling with Docker Compose

You can scale your PostgreSQL service by increasing the number of replicas, but this is generally not recommended for a standalone PostgreSQL container because of data consistency concerns.

If you need to scale PostgreSQL, consider using a more complex setup with replication or clustering. This requires additional configuration and is beyond the scope of this guide.

Clustering and Replication

For advanced use cases, you may want to set up PostgreSQL replication or clustering. This involves configuring multiple PostgreSQL containers to work together, providing high availability and failover capabilities.


Conclusion

Installing PostgreSQL on Docker using Docker Compose is a powerful way to manage your database in a containerized environment. By following this guide, you’ve learned how to set up PostgreSQL with Docker Compose, access the database, manage your containers, customize your setup, and back up your data. This setup is flexible and can serve as a solid foundation for development and production environments.

Whether you’re working on a small project or a large-scale application, Docker and PostgreSQL together offer a robust solution that is easy to deploy, maintain, and scale.

Fedya Serafiev

Fedya Serafiev

Fedya Serafiev owns the website linuxcodelab.eu. He finds satisfaction in helping people solve even the most complex technical problems. His current goal is to write easy-to-follow articles so that such problems do not arise at all.

Thank you for reading the article! If you found the information useful, you can donate using the buttons below: