Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 21

Local PostgreSQL with Docker for Spring Applications

This lesson is built with resources from youtube.com, spring.io and 1 more site.

Welcome to Module 4! In our last module, we took a deep dive into Spring MVC's request lifecycle. By stepping through the framework's code with a debugger, you uncovered the "magic" behind how Spring routes requests, resolves method arguments like Pageable, and converts your DTOs into JSON responses. This gave you a foundational understanding of the web layer.

Now, we shift our focus from handling requests to managing the data itself. Our blog platform currently stores posts in a simple in-memory list, which is lost every time the application restarts. To build a real application, we need a persistent data store. This module, Data Persistence with JPA and PostgreSQL, will guide you through connecting your application to a professional-grade database.

Today's lesson addresses the very first step: running a PostgreSQL instance locally using Docker and connecting the Spring application to it via application.yml properties. By the end of this session, our Spring Boot application will be successfully communicating with a real database, setting the stage for all future data operations.

1. Why Docker for Local Databases?

In the MERN world, you're likely familiar with running a MongoDB instance in a Docker container for local development. This practice is standard across modern software engineering for several reasons:

  • Isolation: The database runs in a self-contained environment, preventing conflicts with other software or database versions on your machine.
  • Reproducibility: Your docker-compose.yml file defines the exact database version and configuration, ensuring every developer on the team has an identical setup.
  • Simplicity: You don't need to follow complex installation guides for different operating systems. A single docker compose up command is all it takes.

We will adopt this same professional workflow for our PostgreSQL database.


2. Setting up PostgreSQL with Docker Compose

Our goal is to define a PostgreSQL service that our Spring application can connect to. We'll use Docker Compose to orchestrate this.

First, create a docker-compose.yml file in the root directory of your Spring Boot project. This file is the equivalent of your package.json for defining services rather than code dependencies.

Docker Compose Configuration for PostgreSQL
This image shows a typical `docker-compose.yml` file. Notice the key sections: `image` specifies the software, `environment` configures it, and `ports` exposes it to your local machine.

The following video demonstrates how to create this file and configure the essential properties for a PostgreSQL container.

Spring Boot Docker and PostgreSQL

In this clip from 'Spring Boot Docker and PostgreSQL' by Dan Vega, you'll see how to create a docker-compose.yml file and define a PostgreSQL service from scratch.

Watch from 05:10 to 06:49. Focus on understanding the purpose of each key in the docker-compose.yml file: services: The top-level key for defining containers. db: The name we're giving our PostgreSQL service. image: Specifies the Docker image to use (e.g., postgres:alpine). ports: Maps the host machine's port to the container's port ('5432:5432'). The format is HOST_PORT:CONTAINER_PORT. environment: Sets environment variables inside the container, used here to configure the initial user, password, and database name.

Based on the video, create your docker-compose.yml file with the following content. We'll use the standard postgres image and name our database blog_platform_db.

version: '3.8'
services:
  db:
    image: postgres:15-alpine
    container_name: blog-db
    ports:
      - '5432:5432'
    environment:
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=blog_platform_db
    restart: unless-stopped

Once the file is saved, open a terminal in your project root and run the container:

docker compose up -d

The -d flag runs the container in detached mode. You can verify it's running with docker ps. You should see a container named blog-db running and listening on port 5432.


3. Connecting Spring Boot to PostgreSQL

Now that our database is running, we need to tell our Spring application how to find it. This is analogous to setting the MONGO_URI in a .env file for a Node.js application.

In Spring Boot, database connection details are configured in src/main/resources/application.yml under the spring.datasource property.

First, ensure your pom.xml includes the necessary dependencies. You should already have spring-boot-starter-data-jpa from Spring Initializr. You must also have the PostgreSQL driver.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

Now, let's add the configuration.

Spring Boot Docker and PostgreSQL

This next clip from the same Dan Vega video shows exactly how to add the datasource properties to your Spring Boot application configuration.

Watch from 07:12 to 07:59. The video uses an application-dev.yaml file, but for now, you can add these properties directly to your main application.yml.

Add the following properties to your src/main/resources/application.yml:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/blog_platform_db
    username: admin
    password: password
    driver-class-name: org.postgresql.Driver

Let's break down the url:

  • jdbc:postgresql:: This is the protocol for connecting to a PostgreSQL database via Java Database Connectivity (JDBC).
  • //localhost:5432: The host and port where the database is listening. This matches the port we mapped in docker-compose.yml.
  • /blog_platform_db: The name of the database we want to connect to, matching POSTGRES_DB.

4. Verification and Debugging

The ultimate test is to run the application.

1. The Happy Path:
With your PostgreSQL container running, start your Spring Boot application from your IDE.

If the connection is successful, the application will start up without errors. In the console logs, you will see output from HikariDataSource, which is the default connection pool used by Spring Boot. It will look something like this:

INFO 23811 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
INFO 23811 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.

2. The Debugging Scenario (Connection Failure):
Now, let's see what happens when things go wrong. This is a very common real-world problem.

  1. Stop the database container: docker compose down.
  2. Try to start your Spring Boot application again.

This time, the application will fail to start. The console will print a long stack trace. This is your first major debugging opportunity in the data layer. Look for the root cause in the error messages. You will see something like:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' ...
...
Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

This error is explicit: the application tried to connect to localhost:5432 but was refused. Your first instinct should be to check if the database container is running and correctly mapped to that port.


5. The "Magic" Way: Spring Boot 3.1+ Docker Compose Integration

Manually configuring the datasource works perfectly, but modern Spring Boot offers an even more streamlined approach. If you add the spring-boot-docker-compose dependency, Spring can automatically detect your docker-compose.yml, start the services, and configure the connection for you—no spring.datasource properties needed!

While this sounds great, it can lead to confusing behavior if you don't understand how it works. The next video is a brilliant demonstration of a common pitfall.

Spring Docker Compose Module - Connecting to the Container Database

In 'Spring Docker Compose Module', Dan Vega explains the new Docker Compose integration and debugs a common issue where external tools can't connect to the database, even though the Spring app can.

This is an essential watch. Follow along from 02:22 to 10:44. Pay close attention to: The docker-compose-support dependency. The difference between port mapping '5432:5432' (fixed host port) and just '5432' (random host port). How he uses a CommandLineRunner to debug the actual JDBC URL that Spring autoconfigured. The final solution: explicitly mapping the port for predictable local development.

The key takeaway from this video is that while Spring's autoconfiguration is powerful, being explicit in your docker-compose.yml (e.g., '5432:5432') is crucial for a predictable development environment where you can connect with external tools like IntelliJ's database client or pgAdmin. For our project, we will stick to this explicit mapping.

For more background on this feature, the official Spring blog provides a concise explanation.

Docker Compose Support in Spring Boot 3.1

The official blog post, 'Docker Compose Support in Spring Boot 3.1', explains the motivation behind this feature and how it simplifies development.

Read the sections that explain the problem with random ports and how Spring Boot 3.1 solves it. This will solidify your understanding of the concepts shown in the video.


Conclusion

Congratulations on connecting your application to a persistent database! You've taken a critical step in moving from a toy application to a real, data-driven service.

Key Takeaways:

  • Docker Compose is the industry standard for managing local development services like databases, providing isolation and reproducibility.
  • Spring Boot connects to a database via properties in application.yml under spring.datasource, specifying the JDBC URL, username, and password.
  • A failed database connection is a common startup error. Reading the stack trace to find Connection refused is a key debugging skill.
  • While Spring Boot 3.1+ can auto-configure connections from docker-compose.yml, explicit port mapping ('HOST:CONTAINER') is recommended for a stable and debuggable local setup.

Preview of the Next Lesson:

Our application can now talk to the database, but the database is empty. In our next lesson, we will define our first JPA Entity. You will learn how to map a Java class to a database table using annotations like @Entity and @Id, and instruct Spring to automatically create the table schema for you.