Docker Run Postgres with User and Password: A Secure Approach Using Docker Compose in 2024

1. Introduction

In the world of containerized applications, using docker run Postgres with user and password is a common requirement. While the traditional docker run command can accomplish this task, Docker Compose offers a more robust and manageable solution. This blog post will guide you through the process of setting up a PostgreSQL container with a custom user and password using Docker Compose, providing you with a secure and scalable database environment.

Docker Compose simplifies the process of defining and running multi-container Docker applications. For PostgreSQL, it allows us to easily specify configuration options, set up networking, and manage persistent data volumes. By using Compose, we can create a repeatable and version-controlled database setup that’s easy to share and deploy across different environments.

2. Prerequisites

Before we dive into the setup process, ensure you have the following prerequisites in place:

  1. Docker: Install Docker on your system. Visit the official Docker website for installation instructions specific to your operating system.
  2. Docker Compose: Docker Compose is included with Docker Desktop for Windows and macOS. For Linux, you may need to install it separately. Check the official Docker Compose documentation for installation guidelines.
  3. Basic knowledge: Familiarity with YAML syntax and basic PostgreSQL concepts will be helpful. Don’t worry if you’re new to these; we’ll explain the essential parts as we go along.
  4. Text editor: Have a text editor ready to create and edit the Docker Compose file. Any text editor will do, but one with YAML syntax highlighting (like Visual Studio Code, Sublime Text, or Atom) can be particularly helpful.

3. Understanding Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services, networks, and volumes. Then, with a single command, you create and start all the services from your configuration.

Key benefits of using Docker Compose for our PostgreSQL setup include:

  1. Declarative configuration: You can define your entire PostgreSQL environment in a single docker-compose.yml file, making it easy to version control and share.
  2. Simplified management: Start, stop, and rebuild services with a single command, making it easier to manage your database container.
  3. Environment variables: Easily set and manage environment variables, including sensitive information like passwords.
  4. Network handling: Compose automatically creates a network for your services, simplifying container-to-container communication.
  5. Volume management: Easily define and manage persistent volumes for your PostgreSQL data.
  6. Scalability: While not as crucial for a single PostgreSQL instance, Compose makes it easy to scale and add additional services as your project grows.

By using Docker Compose instead of a plain docker run command, we gain these advantages while still maintaining the flexibility to customize our PostgreSQL setup with a custom user and password.

In the next section, we’ll start setting up our project structure and create our Docker Compose file.

4. Setting Up the Project Structure

Let’s start by creating a new directory for our project and setting up the necessary files:

  1. Create a new directory for your project:
Bash
   mkdir postgres-docker-compose
   cd postgres-docker-compose
  1. Create a new file named docker-compose.yml in this directory:
   touch docker-compose.yml
  1. Open the docker-compose.yml file in your preferred text editor.

This docker-compose.yml file will be the heart of our PostgreSQL setup, defining how our database container should be configured and run.

5. Writing the Docker Compose File

Now, let’s write our Docker Compose file. We’ll start with a basic setup and then explain each part:

docker-compose.yml
version: '3.8'

services:
  postgres:
    image: postgres:13
    container_name: my_postgres
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: mydatabase
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    restart: unless-stopped

volumes:
  postgres_data:

This Docker Compose file defines a single service named postgres using the official PostgreSQL 13 image. It sets up environment variables for the user, password, and database name, creates a persistent volume for data storage, and maps the container’s port to the host.

6. Detailed Compose File Explanation

Let’s break down each part of the Docker Compose file:

  • version: '3.8': This specifies the version of the Docker Compose file format we’re using.
  • services:: This section defines the containers we want to run.
  • postgres:: This is the name of our service.
  • image: postgres:13: This specifies the Docker image to use. We’re using the official PostgreSQL 13 image.
  • container_name: my_postgres: This sets a custom name for our container.
  • environment:: This section allows us to set environment variables for the container.
  • POSTGRES_USER: myuser: Sets the PostgreSQL user to ‘myuser’.
  • POSTGRES_PASSWORD: mypassword: Sets the password for the user to ‘mypassword’.
  • POSTGRES_DB: mydatabase: Creates a database named ‘mydatabase’.
  • volumes:: This section defines the volumes to be used.
  • - postgres_data:/var/lib/postgresql/data: This creates a named volume ‘postgres_data’ and mounts it to the container’s data directory.
  • ports:: This section maps container ports to host ports.
  • - "5432:5432": This maps the container’s PostgreSQL port (5432) to the same port on the host.
  • restart: unless-stopped: This tells Docker to always restart the container unless it’s explicitly stopped.
  • volumes:: This section at the root level defines named volumes that can be used by services.
  • postgres_data:: This creates a named volume that will persist the database data.

With this configuration, you now have a basic PostgreSQL setup using Docker Compose that includes a custom user and password.

7. Running the PostgreSQL Container

Now that we have our Docker Compose file set up, let’s run our PostgreSQL container:

  1. Open a terminal and navigate to your project directory containing the docker-compose.yml file.
  2. Run the following command to start the container:
Bash
   docker-compose up -d

The -d flag runs the container in detached mode, allowing it to run in the background.

  1. To verify that the container is running, use the following command:
Bash
   docker-compose ps

You should see your PostgreSQL container listed as running.

  1. To view the logs of your container, use:
Bash
   docker-compose logs postgres

This will show you the startup logs of your PostgreSQL container.

8. Security Best Practices

When working with databases, especially in containerized environments, security is paramount. Here are some best practices to enhance the security of your PostgreSQL setup:

  1. Use Environment Variables: Instead of hardcoding sensitive information like passwords in your docker-compose.yml file, use environment variables. Create a .env file in your project directory:
Bash
   POSTGRES_USER=myuser
   POSTGRES_PASSWORD=mypassword
   POSTGRES_DB=mydatabase

Then, update your docker-compose.yml to use these variables:

YAML
   services:
     postgres:
       environment:
         POSTGRES_USER: ${POSTGRES_USER}
         POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
         POSTGRES_DB: ${POSTGRES_DB}

Don’t forget to add .env to your .gitignore file to avoid committing sensitive information to version control.

  1. Implement Docker Secrets: For even better security, especially in a Docker Swarm environment, use Docker secrets. This is a more advanced topic, but worth considering for production environments.
  2. Restrict Network Access: If your PostgreSQL instance doesn’t need to be accessible from outside the Docker network, remove the ports section from your Compose file. This prevents the database from being exposed on your host machine.
  3. Use Strong Passwords: Ensure you’re using strong, unique passwords for your database users. Consider using a password manager or a secure password generation tool.
  4. Regular Updates: Keep your PostgreSQL image up to date by regularly pulling the latest version and rebuilding your container. This ensures you have the latest security patches.

9. Conclusion

In this blog post, we’ve walked through the process of setting up a docker-compose file for docker run postgres with user and password. We’ve covered:

  • The advantages of using Docker Compose for PostgreSQL setup
  • Creating a project structure and writing a Docker Compose file
  • Detailed explanation of each component in the Compose file
  • Running the PostgreSQL container and verifying its status
  • Security best practices for your containerized PostgreSQL instance

By using Docker Compose, we’ve created a reproducible and easily manageable PostgreSQL environment. This approach allows for easy version control of your database configuration and simplifies the process of setting up development, testing, and production environments.

For your reference, you can find the complete code and configuration files used in this blog post in our GitHub repository: https://github.com/NickyBall/docker-postgres-template

Remember, while this setup is a great starting point, always consider the specific needs of your project and the environment in which it will run. As you become more comfortable with Docker and PostgreSQL, you can explore more advanced configurations and optimizations.

Happy coding!!

Leave a Comment