Home Java javaTutorial Building and Deploying Your First Java App with Docker in Just inutes

Building and Deploying Your First Java App with Docker in Just inutes

Jan 14, 2025 am 09:42 AM

Building and Deploying Your First Java App with Docker in Just inutes

Let's create a simple java app which returns text and available on port 1800 of your local environment using Docker container in 5 minutes (depends on your internet connection speed).

You can always grab the full source code from my public repository:
https://github.com/alexander-uspenskiy/simple-service

Dependencies Setup

Step 1: Prerequisites

  1. Install Java 8
  2. Install Maven
  3. Install Docker
  4. Install VS Code Extensions

Mac Installation

# Install Homebrew if not present
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Java 8
brew tap homebrew/cask-versions
brew install --cask temurin8

# Install Maven
brew install maven

# Install Docker Desktop
brew install --cask docker

# Install VS Code
brew install --cask visual-studio-code

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker
Copy after login
Copy after login

Windows Installation

# Install Chocolatey if not present
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install Java 8
choco install temurin8

# Install Maven
choco install maven

# Install Docker Desktop
choco install docker-desktop

# Install VS Code
choco install vscode

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker
Copy after login
Copy after login

Project Setup (Both Platforms)

# Create project structure
mkdir -p simple-service
cd simple-service
Copy after login

VS Code Settings

{
    "java.configuration.runtimes": [
        {
            "name": "JavaSE-1.8",
            "path": "/Library/Java/JavaVirtualMachines/temurin-8.jdk/Contents/Home",
            "default": true
        }
    ],
    "java.configuration.updateBuildConfiguration": "automatic",
    "java.compile.nullAnalysis.mode": "automatic",
    "maven.executable.path": "/usr/local/bin/mvn"
}
Copy after login

Verify Installation

# Verify Java
java -version

# Verify Maven
mvn -version

# Verify Docker
docker --version
Copy after login

Project Setup

# Create Maven project
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=simple-service \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DarchetypeVersion=1.4 \
  -DinteractiveMode=false
Copy after login

Creating the test app

After the last step you should have simple-service directory with the pre-builded structure.

Step 1

  1. Update pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>simple-service</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>simple-service</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.4</version>
    </dependency>
</dependencies>
<properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.App</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
Copy after login

Step 2

Add logic to App.java

package com.example;

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.io.OutputStream;

public class App {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(1800), 0);
        server.createContext("/", (exchange -> {
            String response = "Hello from Java!";
            exchange.sendResponseHeaders(200, response.length());
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        }));
        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port 1800");
    }
}
Copy after login

Quick explanations:

  1. Imports & Setup

    • Uses built-in com.sun.net.httpserver package
    • Creates simple HTTP server without external dependencies
    • Runs on port 1800
  2. Server Configuration

HttpServer.create()

  • Creates new server instance

InetSocketAddress(1800)

  • Binds to port 1800
  • 0 - Default backlog value for connection queue
  1. Request Handling

createContext("/")

  • Handles all requests to root path "/"
  • Lambda expression defines request handler
  • Returns "Hello from Java!" for all requests
  1. Response Flow

    • Sets response code 200 (OK)
    • Sets content length
    • Writes response bytes to output stream
    • Auto-closes stream with try-with-resources
  2. Server Start

setExecutor(null)

  • Uses default executor

server.start()

  • Starts listening for requests
  • Prints confirmation message

Step 3

Create Dockerfile in the root of the project:

FROM amazoncorretto:8
WORKDIR /app
COPY target/simple-service-1.0-SNAPSHOT.jar app.jar
EXPOSE 1800
CMD ["java", "-jar", "app.jar"]
Copy after login

Step 4
Create docker-compose.yml to build and map container to port 1800

services:
  app:
    build: .
    ports:
      - "1800:1800"
    restart: unless-stopped
Copy after login

Step 5
Create build.sh

#!/bin/bash
mvn clean package
docker compose build
docker compose up
Copy after login

And allow exec permission for this file in terminal:

# Install Homebrew if not present
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Java 8
brew tap homebrew/cask-versions
brew install --cask temurin8

# Install Maven
brew install maven

# Install Docker Desktop
brew install --cask docker

# Install VS Code
brew install --cask visual-studio-code

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker
Copy after login
Copy after login

Build and execute the app

Simply run

# Install Chocolatey if not present
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install Java 8
choco install temurin8

# Install Maven
choco install maven

# Install Docker Desktop
choco install docker-desktop

# Install VS Code
choco install vscode

# Install VS Code Extensions
code --install-extension vscjava.vscode-java-pack
code --install-extension ms-azuretools.vscode-docker
Copy after login
Copy after login

You should have project builded, image created and container executed.

To test the app simply open the browser at the address http://localhost:1800/

Happy Coding!

The above is the detailed content of Building and Deploying Your First Java App with Docker in Just inutes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles