Spring Boot with Docker and Kubernetes: Containerizing and Deploying Your Java Applications

Igor Venturelli - Oct 30 - - Dev Community

Dockerize and deploy Spring Boot apps with Kubernetes for scalable and consistent deployment

In today's fast-paced development world, containerization has become a cornerstone for deploying applications efficiently and consistently. Docker is at the forefront of this revolution, enabling developers to package applications and their dependencies into containers. Once your applications are containerized, Kubernetes steps in to orchestrate and manage these containers at scale. This blog post explores how to containerize your Spring Boot applications using Docker and deploy them using Kubernetes, ensuring seamless deployment and scalability.

What is Docker?

Docker is an open-source platform that automates the deployment of applications inside lightweight, portable containers. Containers provide a standardized environment, encapsulating everything an application needs to run: code, runtime, system tools, libraries, and settings. This ensures that applications behave the same way in different environments, from development to production.

How Docker Works

Docker uses a client-server architecture. The Docker client communicates with the Docker daemon, which builds, runs, and manages Docker containers. At the core of Docker's functionality are images and containers:

  • Docker Image: A read-only template that contains the application code and all dependencies required to run an application. Think of it as a snapshot of your application environment.
  • Docker Container: A runnable instance of a Docker image. Containers are isolated but can communicate with each other through defined channels.

Containerizing Spring Boot Applications

Spring Boot applications can be easily containerized to ensure consistency across different environments. Let's dive into creating Docker images for your Spring Boot applications.

Creating a Docker Image for a Spring Boot Application

  1. Create a Spring Boot Application: If you haven't already, create a simple Spring Boot application using Spring Initializr. For example:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController
class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Docker!";
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create a Dockerfile: A Dockerfile is a script containing a series of commands to assemble your image.
# Use the official OpenJDK image as a base
FROM openjdk:17-jdk-alpine

# Set the working directory
WORKDIR /app

# Copy the Spring Boot jar file into the container
COPY target/demo-0.0.1-SNAPSHOT.jar app.jar

# Expose the application port
EXPOSE 8080

# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]
Enter fullscreen mode Exit fullscreen mode
  1. Build the Docker Image: Run the following command in the directory containing the Dockerfile to build your Docker image:
docker build -t my-spring-boot-app .
Enter fullscreen mode Exit fullscreen mode
  1. Run the Docker Container: Use the following command to run a container from the image:
docker run -p 8080:8080 my-spring-boot-app
Enter fullscreen mode Exit fullscreen mode

Your Spring Boot application should now be accessible at http://localhost:8080/hello.

Deploying with Kubernetes

Kubernetes is an open-source platform that automates the deployment, scaling, and management of containerized applications. It abstracts the underlying infrastructure, providing a unified API to manage resources across different environments.

Deploying a Spring Boot Application on Kubernetes

  1. Create a Kubernetes Deployment: A Deployment in Kubernetes manages a set of replicas of your application, ensuring the desired state is always met.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: spring-boot-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: spring-boot-app
  template:
    metadata:
      labels:
        app: spring-boot-app
    spec:
      containers:
      - name: spring-boot-app
        image: my-spring-boot-app
        ports:
        - containerPort: 8080
Enter fullscreen mode Exit fullscreen mode
  1. Create a Kubernetes Service: A Service exposes your application to the outside world and load balances traffic across your replicas.
apiVersion: v1
kind: Service
metadata:
  name: spring-boot-service
spec:
  type: LoadBalancer
  selector:
    app: spring-boot-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
Enter fullscreen mode Exit fullscreen mode
  1. Deploy on Kubernetes: Use the following commands to apply your configuration files and deploy your application on a Kubernetes cluster:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
Enter fullscreen mode Exit fullscreen mode

Security Best Practices for Docker Images

When working with Docker, security should always be a priority. Here are some best practices to avoid threats related to Docker images:

  1. Use Official Images: Always start with official or trusted images from Docker Hub to reduce vulnerabilities.
  2. Minimize the Image Size: Use minimal base images (e.g., alpine) to reduce the attack surface.
  3. Scan Images for Vulnerabilities: Regularly scan your Docker images for known vulnerabilities using tools like Docker Scan or Clair.
  4. Run as Non-Root User: Avoid running applications as the root user inside containers. Specify a non-root user in your Dockerfile.
# Add a user
RUN adduser -D myuser
USER myuser
Enter fullscreen mode Exit fullscreen mode
  1. Limit Resource Usage: Use Docker’s resource limits to restrict the CPU and memory usage of your containers.
docker run -p 8080:8080 --memory="512m" --cpus="1.0" my-spring-boot-app
Enter fullscreen mode Exit fullscreen mode

Conclusion

Dockerizing your Spring Boot applications simplifies deployment and scaling, ensuring consistency across environments. By using Kubernetes for orchestration, you can manage your containers efficiently and scale them as needed. By following best practices for security, you can protect your applications from potential threats. Whether you're developing on your local machine or deploying in a production environment, Docker and Kubernetes provide the tools to make the process seamless and efficient.

Embrace the power of containerization and orchestration to take your Spring Boot applications to the next level!


Let’s connect!

📧 Don't Miss a Post! Subscribe to my Newsletter!
➡️ LinkedIn
🚩 Original Post
☕ Buy me a Coffee

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .