Database Connection

In this lesson, we'll set up PostgreSQL using Docker and configure our Spring Boot application to connect to it.

Set Up PostgreSQL with Docker

Docker makes running PostgreSQL simple and consistent across different development environments. Let's create a docker-compose.yml file to define our database setup:

services: db: image: postgres:latest ports: - '5432:5432' restart: always environment: POSTGRES_PASSWORD: changemeinprod! adminer: image: adminer:latest restart: always ports: - 8888:8080

This configuration sets up two services:

  • A PostgreSQL database running on port 5432
  • Adminer, a web-based database management tool, running on port 8888

To start these services, run:

docker-compose up

Configure Spring Boot Database Connection

Our application needs to know how to connect to PostgreSQL. We'll configure this in application.properties:

# Database Connection spring.datasource.url=jdbc:postgresql://localhost:5432/postgres spring.datasource.username=postgres spring.datasource.password=changemeinprod! # JPA Configuration spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

The database connection properties tell Spring Boot:

  • Where to find the database (localhost:5432)
  • Which database to use (postgres)
  • The login credentials

The JPA configuration enables:

  • Automatic table creation and updates based on our entity classes
  • SQL logging for development debugging
  • PostgreSQL-specific SQL dialect for optimal database interaction

Development Best Practices

When working with databases in development:

  • Never store real passwords in configuration files
  • Use environment variables or secure configuration management in production
  • Consider using database migration tools like Flyway for production deployments
  • Keep the SQL logging enabled only in development for debugging

Summary

  • PostgreSQL runs in Docker for consistent local development
  • Adminer provides a web interface for database management
  • Spring Boot connects to PostgreSQL using configuration properties
  • JPA automatically manages database schema changes
© 2026 Devtiro Ltd. All rights reserved