Skip to main content

Building Your First Docker Image for Java Spring Boot REST service

· 6 min read

Building Your First Docker Image for a Java Spring Boot REST service is a streamlined process, encapsulating your application into a portable, self-sufficient container. This enables easy deployment across diverse environments, ensuring consistent execution of your RESTful service. Utilizing Docker, you package your Spring Boot application, facilitating scalability, reproducibility, and efficient management of dependencies, making deployment a breeze.

1. Prerequisites

1.1. Install Java Development Kit (JDK)

1.1.1. Download the JDK

Visit Oracle JDK Download Page and select the appropriate version for your operating system. You might need to create an Oracle account or log in to download it.

1.1.2. Choose the Right Version

Ensure you're downloading the version suitable for your operating system (Windows, macOS, Linux) and system architecture (32-bit or 64-bit).

1.1.3. Install the JDK

  1. Windows: Execute the downloaded .exe file and follow the installation wizard instructions.
  2. macOS: Double-click the downloaded .dmg file anf follow the instructions in the installer to complete the installation.
  3. Linux: Use package management tools like apt, yum, or dnf based on your distribution.
bash
sudo apt update
sudo apt install default-jdk

1.1.4. Set Java Environment Variables (if not set automatically)

  1. Windows: Set the JAVA_HOME and PATH environment variables:
    1. Right-click on 'This PC' or 'My Computer', then select 'Properties'.
    2. Go to 'Advanced system settings'.
    3. Click on 'Environment Variables'.
    4. Under 'System Variables', click 'New' and add JAVA_HOME with the path to your JDK installation (e.g., C:\Program Files\Java\jdk1.8.0_241).
    5. Find the 'Path' variable, click 'Edit', and add %JAVA_HOME%\bin to the list of paths.
  2. macOS and Linux: Environment variables might be set automatically. You can verify by running java -version and javac -version in the terminal.

1.1.5. Verify Installation

Open a terminal or command prompt and type:

bash
java -version
javac -version

This should display the installed Java version, confirming that the installation was successful.

1.2. Install Maven (or Gradle)

1.2.1. Download Maven

Visit the Apache Maven Download Page and download the latest version of Maven.

1.2.2. Choose the Right Version

Select the binary zip archive appropriate for your operating system.

1.2.3. Install

  1. Windows: Extract the downloaded zip file to a directory where you want Maven to be installed (e.g., C:\Program Files\Maven).
  2. macOS/Linux: Extract the downloaded archive to a directory of your choice, often /usr/local/apache-maven, or use a package manager if available.

1.2.4. Set Maven Environment Variables

  1. Windows:
    1. Right-click on 'This PC' or 'My Computer', then select 'Properties'.
    2. Go to 'Advanced system settings'.
    3. Click on 'Environment Variables'.
    4. Under 'System Variables', click 'New' and add M2_HOME with the path to your Maven installation (e.g., C:\Program Files\Maven).
    5. Find the 'Path' variable, click 'Edit', and add %M2_HOME%\bin to the list of paths.
  2. macOS and Linux: Edit the .bash_profile, .bashrc, or .zshrc file to add Maven to the PATH variable. Open the file in a text editor and add:
    bash
    export PATH=/path/to/apache-maven/bin:$PATH
    Replace /path/to/apache-maven with the actual path to your Maven installation directory.
  3. Verify Maven Installation: Open a terminal or command prompt and type:
bash
mvn -version

This should display the installed Maven version, confirming that the installation was successful.

1.3. Install Gradle (or Maven)

1.3.1. Download Gradle

Visit the Gradle Releases Page and download the latest version of Gradle.

1.3.2. Choose the Right Version

Select the binary-only distribution appropriate for your operating system.

1.3.3. Install

  1. Windows: Extract the downloaded zip file to a directory where you want Gradle to be installed (e.g., C:\Program Files\gradle).
  2. macOS/Linux: Extract the downloaded archive to a directory of your choice, often /usr/local/gradle, or use a package manager if available.

1.3.4. Set Gradle Environment Variables

  1. Windows:
    1. Right-click on 'This PC' or 'My Computer', then select 'Properties'.
    2. Go to 'Advanced system settings'.
    3. Click on 'Environment Variables'.
    4. Under 'System Variables', click 'New' and add GRADLE_HOME with the path to your Gradle installation (e.g., C:\Program Files\Gradle).
    5. Find the 'Path' variable, click 'Edit', and add %GRADLE_HOME%\bin to the list of paths.
  2. macOS and Linux: Edit the .bash_profile, .bashrc, or .zshrc file to add Gradle to the PATH variable. Open the file in a text editor and add:
    export PATH=/path/to/gradle/bin:$PATH
    Replace /path/to/gradle with the actual path to your Gradle installation directory.
  3. Verify Gradle Installation: Open a terminal or command prompt and type:
gradle -version

This should display the installed Gradle version, confirming that the installation was successful.

1.4. Install Docker

1.4.1. Windows

1.4.1.1. Requirements
  1. Windows 10 64-bit: Pro, Enterprise, or Education
  2. Hyper-V and Containers Windows features enabled
1.4.1.2. Download Docker Desktop
  1. Go to the Docker Desktop for Windows page.
  2. Click on "Download for Windows" and follow the instructions to download the installer.
1.4.1.3. Install Docker Desktop
  1. Run the downloaded installer.
  2. Follow the on-screen instructions for installation. It might require system restarts.
1.4.1.4. Start Docker
  1. After installation, Docker Desktop should start automatically.
  2. Look for the Docker icon in the system tray and ensure it indicates that Docker is running.

1.4.2. macOS:

1.4.2.1. Requirements
  1. macOS version 10.13 or newer
1.4.2.2. Download Docker Desktop
  1. Go to the Docker Desktop for Mac page.
  2. Click on "Download for Mac" and follow the instructions to download the installer.
1.4.2.3. Install Docker Desktop
  1. Run the downloaded installer (.dmg file).
  2. Drag the Docker icon to the Applications folder.
1.4.2.4. Start Docker
  1. Open the Applications folder and click on Docker.
  2. Docker should start and indicate that it's running in the menu bar.

1.4.3. Linux

1.4.3.1. Requirements
  1. A compatible Linux distribution. Docker supports many distributions. Refer to the official Docker documentation for specific requirements for your distribution.
1.4.3.2. Install Docker Engine
  1. Follow the instructions in the official Docker documentation for your specific Linux distribution.
  2. Usually involves adding Docker's official GPG key, adding the Docker repository, installing the Docker Engine, and starting the Docker service.
1.4.3.3. Manage Docker as a non-root user (Optional)
  1. Add your user to the docker group to avoid using sudo with Docker commands:
bash
sudo usermod -aG docker ${USER}

Log out and log back in or restart your system for changes to take effect.

1.4.3.4. Start Docker
  1. After installation, start the Docker service:
bash
sudo systemctl start docker
  1. Enable Docker to start on boot:
bash
sudo systemctl enable docker
1.4.3.5. Verify Docker Installation
  1. Run a simple Docker command to verify the installation, like:
docker --version

2. Create a Spring Boot Application using Spring Initializr

2.1. Access Spring Initializr

Go to the Spring Initializr website.

2.2. Configure your project

  1. Project: Select Maven or Gradle as the build tool.
  2. Language: Choose Java or Kotlin.
  3. Spring Boot: Choose the desired version of Spring Boot.
  4. Group: Enter a unique group identifier (e.g., com.example).
  5. Artifact: Define the name of your application (e.g., my-spring-boot-app).
  6. Dependencies: Add the necessary dependencies for your project. For example: 1.** Spring Web:** To build web applications. 2. Other dependencies based on your project requirements (like Spring Data JPA, Spring Security, Thymeleaf, etc.).

2.3. Generate the Project

Click on the "Generate" button. This action will create and download a zip file containing the Spring Boot project with your specified configurations and dependencies.

2.4. Extract and Import the Project

Extract the downloaded zip file to your preferred directory.

2.5. Import into Your IDE

  1. Import the extracted project into your favorite Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or VS Code.
  2. If you're using IntelliJ IDEA:
    1. Open IntelliJ IDEA.
    2. Select "Open" or "Import" and choose the folder containing the extracted project.
    3. IntelliJ should recognize it as a Maven or Gradle project and set it up accordingly.

2.6. Start Developing

  1. Once imported, you can start coding your Spring Boot application.
  2. The src/main/java directory will contain your main application class.
  3. Additional folders like src/main/resources will hold configurations and static resources.

2.7. Run the Application

Locate the main application class (usually annotated with @SpringBootApplication) and run it. This starts your Spring Boot application.

This process will create a basic Spring Boot application with the dependencies and structure you specified in Spring Initializr. You can then add your custom code, controllers, services, and more as per your application's requirements.

3. Add a Spring Boot GetMapping REST controller

src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;

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!";
}
}

4. Build the Spring Boot Application

Use Maven or Gradle to build your Spring Boot application. If using Maven, run:

bash
mvn clean package

5. Creating a Dockerfile

Create a Dockerfile in the root of your project to define the Docker image:

Dockerfile
# Use a base image with Java installed
FROM openjdk:11-jre-slim

# Set the working directory in the container
WORKDIR /app

# Copy the JAR file into the container at /app
COPY target/your-application-name.jar /app/app.jar

# Expose the port your app runs on
EXPOSE 8080

# Command to run your application
CMD ["java", "-jar", "app.jar"]

Replace your-application-name.jar with the actual name of your Spring Boot application JAR file.

6. Build the Docker Image

Run the following command in your project directory where the Dockerfile is located:

bash
docker build -t your-image-name .

Replace your-image-name with the desired name for your Docker image.

7. Run the Docker Container

Once the image is built, you can run the Docker container using:

bash
docker run -p 8080:8080 your-image-name

8. Test the Endpoint

Open a web browser or use a tool like curl or Postman to access the endpoint:

bash
curl http://localhost:8080/hello

You should see the response Hello, Docker!