Loading alternative title
Wednesday, January 22, 2025

How to Create a Postgres Database in Docker

1. Install Docker

Ensure Docker is installed and running on your system. If not, download and install it from the Docker website.


2. Pull the PostgreSQL Image

Pull the official PostgreSQL image from Docker Hub:

bash
docker pull postgres

This fetches the latest PostgreSQL image.


3. Run the PostgreSQL Container

Run a PostgreSQL container with the desired configurations:

bash
docker run --name my-postgres -e POSTGRES_USER=myuser -e POSTGRES_PASSWORD=mypassword -e POSTGRES_DB=mydatabase -p 5432:5432 -d postgres

Explanation of Parameters:

  • --name my-postgres: Names the container my-postgres.
  • -e POSTGRES_USER=myuser: Sets the username for the PostgreSQL database.
  • -e POSTGRES_PASSWORD=mypassword: Sets the password for the PostgreSQL database.
  • -e POSTGRES_DB=mydatabase: Creates a database named mydatabase.
  • -p 5432:5432: Maps the container's port 5432 to your local port 5432.
  • -d: Runs the container in detached mode (in the background).
  • postgres: The name of the image.

4. Verify the Container is Running

Check if the container is running:

bash
docker ps

You should see your my-postgres container in the list.


5. Connect to the PostgreSQL Database

You can connect to the PostgreSQL database using:

  1. Command Line:

    bash
    docker exec -it my-postgres psql -U myuser -d mydatabase
    • This logs you into the PostgreSQL database.
  2. Database Client (e.g., DBeaver, pgAdmin):

    • Host: localhost
    • Port: 5432
    • Database: mydatabase
    • Username: myuser
    • Password: mypassword

6. Persisting Data (Optional)

By default, PostgreSQL data is stored in the container. To persist data:

  • Mount a volume to store the database files:
    bash
    docker run --name my-postgres \ -e POSTGRES_USER=myuser \ -e POSTGRES_PASSWORD=mypassword \ -e POSTGRES_DB=mydatabase \ -p 5432:5432 \ -v my-postgres-data:/var/lib/postgresql/data \ -d postgres
  • Replace my-postgres-data with the name of your volume. Data will remain intact even if the container is stopped or removed.

7. Stopping and Starting the Container

  • Stop the container:
    bash
    docker stop my-postgres
  • Start the container:
    bash
    docker start my-postgres

Let me know if you need help with connecting your Spring Boot application to this PostgreSQL instance!

  • Share on:
image title here

Some title