Dockerize Spring Boot Application With PostgresSQL

In recent years, Docker has revolutionized the way in which we deploy and manage applications, offering a lightweight and productive solution for packaging software and its conditions into containers. For developers working with Spring Boot, a well known Java system for building undertaking grade applications, Dockerization gives various advantages concerning conveyability, versatility, and reproducibility of conditions.

This article fills in as a thorough manual for dockerizing a Spring Boot application with PostgreSQL, a strong open-source social data set system. By containerizing our Spring Boot application and its related information base, we can ensure consistency across development, testing, and production conditions, as well as improve on sending and maintenance tasks.

In this guide, we’ll dive into the most common way of Dockerizing a Spring Boot application step by step, beginning from characterizing essential phrasings like Docker, Spring Boot, and PostgreSQL, to giving a definite walkthrough of the dockerization cycle. We’ll cover all that from composing a Dockerfile to designing the Spring Boot application to associate with a PostgreSQL data set running in a Docker container.

Understanding Of Primary Terminologies

  • Docker: Docker is a platform that empowers designers to develop, convey, and run applications in containers. Compartments are lightweight, independent, executable packages that contain everything expected to run an application, including code, runtime, libraries, and conditions. Docker gives apparatuses and APIs to oversee and arrange holders proficiently, making it more straightforward to build, ship, and run applications reliably across various conditions.
  • Spring Boot: Spring Boot is an open-source Java structure based on top of the Spring system. It gives a smoothed out method for making independent, creation grade Spring-based applications with negligible design. Spring Boot improves on the advancement cycle via auto-designing numerous parts of the application, for example, reliance infusion, information base access, and web application advancement. It additionally offers highlights like installed servers, creation prepared measurements, and health checks the container.
  • Dockerfile: A Dockerfile is a text document that contains directions for building a Docker image. It defines the means expected to make a picture by determining the base image, replicating records into the image, setting climate factors, and arranging the runtime environment. Dockerfiles are utilized to automate the method involved with building Docker image and ensure consistency across various arrangements
  • PostgreSQL: PostgreSQL is a strong open-source relational database management system known for its unwavering quality, vigor, and extensibility. It supports a large number of cutting edge highlights, including ACID compliance, full-text search, JSON support, and geospatial information types. PostgreSQL is profoundly adjustable and offers solid help for complex queries and exchanges, settling on it a well known decision for big business applications and information escalated responsibilities.
  • Containerization: Containerization is a lightweight choice to full machine virtualization that encapsulates an application and its conditions into a container. Container give isolation, portability, and consistency across various conditions, allowing developers to package applications once and run them anyplace. Containerization advances like Docker empower developers to make, convey, and oversee compartments effectively, making it simpler to construct and keep up with complex programming systems.

Dockerize Spring Boot Application With Postgress: A Step-By-Step Guide

Step 1: Launch An EC2 instance

  • Firstly we need to login to AWS Management Console with our credentials or create new account.
  • Launch EC2 instance with Amazon Linux2 Kernel 5.10(AMI) along with port numbers set SSH – 22, HTTP 8o and select storage t2.micro.

  • Now connect with terminal

Step 2: Install Docker

  • In our local machine install docker by using following command
sudo yum -y install docker

  • Now start and enable our docker service, without starting of docker we cannot perform our docker services
sudo systemctl start docker 
sudo systemctl enable docker
sudo systemctl status docker

  • Now execute these commands
sudo usermod -aG docker ec2-user
sudo chmod 666 /var/run/docker.sock

  • sudo usermod -aG docker ec2-user: This command adds the user ec2-user to the docker group. This is typically done to grant the user permission to interact with the Docker daemon without needing to use sudo for every Docker command.
  • sudo chmod 666 /var/run/docker.sock: This command changes the permissions of the Docker socket file (/var/run/docker.sock) to allow read and write access for all users on the system.

Step 3: Install Docker Compose

sudo curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose 

  • Now change permissions to docker compose to execute without any sudo permissions
sudo chmod +x /usr/local/bin/docker-compose

Step 4: Spring Initializer

  • Now we need a spring boot application for this, Now you can go to Spring Initializer and generate project and extract to our local machine.

  • Extract files our desktop to local machine by using following command
scp -i <keypairs filename.pem> <downloaded filename> ec2-user@<public ip of instance >: /path .
  • Following figure shows that pom.xml file

  • This will create our basic structure project, Now go to pom.xml file and add dependencies
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

Step 4: Create A Dockerfile For The Spring Boot Application

  • Use the following code and save it with Dockerfile name.
# Dockerfile
FROM openjdk:11-jre-slim
WORKDIR /app
COPY target/your-app.jar /app/your-app.jar
EXPOSE 8080
CMD ["java", "-jar", "your-app.jar"]

Step-5: Create A Dockerfile For PostgreSQL

# Dockerfile-postgres
FROM postgres:latest
COPY postgresql.conf /etc/postgresql/postgresql.conf
COPY init.sql /docker-entrypoint-initdb.d/

Step 6: Create Application Properties For Spring Boot

# application.properties
spring.datasource.url=jdbc:postgresql://postgres:5432/your-database
spring.datasource.username=your-username
spring.datasource.password=your-password
spring.jpa.hibernate.ddl-auto=update

Step 7: Build Docker images

  • Now, build the docker images with the following commands:
# Build Docker image for Spring Boot application
docker build -t your-app-image -f Dockerfile .
# Build Docker image for PostgreSQL
docker build -t postgres-image -f Dockerfile-postgres .
  • Now we can check docker images by using following command
docker images

Step 8: Create Docker-Compose File

  • Now create a docker-compose file with .yml extension. Inside this file we are writing yaml scripting to our docker compose
version: '3.3'

services:
app:
image: 'docker-spring-boot-postgres:latest'
build:
context: .
container_name: app
depends_on:
- db
environment:
- POSTGRES_USER=admin
- POSTGRES_PASSWORD=admin123
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/demo
- SPRING_DATASOURCE_USERNAME=admin #your required name
- SPRING_DATASOURCE_PASSWORD=admin123 # your required password
- SPRING_JPA_HIBERNATE_DDL_AUTO=update
ports:
- "8080:8080"

db:
image: postgres
container_name: db
environment:
- POSTGRES_USER=admin #your required name
- POSTGRES_PASSWORD=admin123 # your required password
- POSTGRES_DB=demo

Step 9: Build And Run The Application

  • We are created docker file and docker-compose file, So we are ready to run our application by using docker-compose command.
docker-compose up -d
  • This command will build and run the Docker image for our Spring Boot application and start the PostgreSQL and application containers. Once the containers are running, we can access the application at http://localhost:8080/users

Conclusion

In conclusion, dockerizing a Spring Boot application with PostgreSQL offers various benefits regarding portability, versatility, and consistency across various conditions. By containerizing the application and its related database, developers can streamline the deployment system, ensure reproducibility of conditions, and work on maintenance tasks.

All through this guide, we explored of the fundamental advances engaged with dockerizing a Spring Boot application, beginning from defining essential terminologies like Docker, Spring Boot, and PostgreSQL, to giving a point by point walkthrough of the dockerization cycle. We examined composing a Dockerfile, designing the Spring Boot application to interface with a PostgreSQL data set running in a Docker container, and organizing container deployment utilizing Docker Compose.

By utilizing Docker and Docker Compose, developers can make independent, versatile conditions for their Spring Boot applications, empowering consistent arrangement across improvement, testing, and creation conditions. Dockerization works with proficient asset usage, upgrades application versatility, and speeds up the improvement lifecycle by giving a reliable and isolated runtime environment.

Dockerize Spring Boot Application – FAQ’s

Why Use Docker For Deploying Spring Boot Applications?

Docker works on application deployment by giving lightweight, compact compartments that embody the application and its conditions.

Why Dockerize A Spring Boot Application With PostgreSQL?

Dockerizing considers the creation of self-contained, convenient conditions, ensuring consistency across various stages and improving on organization processes. It likewise works with versatility, asset improvement, and effective administration of conditions.

Might I Use Utilize Different Data Sets Other Than Postgresql With Docker And Spring Boot?

Yes, Docker supports different database systems, including MySQL, MongoDB, and Redis. Spring Boot offers help for numerous information bases through its strong information access structure, allowing developers to pick the most appropriate database for their application necessities.

How Might I Optimize Docker Images For Spring Boot Applications?

To enhance Docker images, engineers can use strategies, for example, multi-stage builds to diminish images size, limit the quantity of layers, and utilize Elevated Linux as a lightweight base images. Moreover, utilizing Docker reserving and eliminating pointless conditions can additionally further build images fabricate times and runtime execution.

How Does Docker Compose On The Management Out Of Multi-compartment Applications?

Docker Create is a tool for defining and running multi-container Docker applications. It allows developers to characterize application benefits, their conditions, and organization setups in a solitary YAML record. Docker Make works on the orchestration of complicated application stacks, empowering developers to deal with multiple containers as a single unit.

Is Docker suitable for production deployments of Spring Boot applications?

Yes, Docker is broadly utilized production environments for deploying Spring Boot applications because of its versatility, unwavering quality, and asset isolation highlights. Docker gives robust container orchestration instruments like Docker Swarm and Kubernetes, which further upgrade the organization and the executives of creation jobs.



Contact Us