search
HomeJavajavaTutorialBuilding and Deploying Your First Java App with Docker in Just inutes

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

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

Project Setup (Both Platforms)

# Create project structure
mkdir -p simple-service
cd simple-service

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

Verify Installation

# Verify Java
java -version

# Verify Maven
mvn -version

# Verify Docker
docker --version

Project Setup

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

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>

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

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"]

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

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

Step 5
Create build.sh

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

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

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

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
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function