讓我們創建一個簡單的java 應用程序,它返回文本並在5 分鐘內使用Docker 容器在本地環境的端口1800 上可用(取決於您的互聯網連接速度) 。
您隨時可以從我的公共儲存庫取得完整的原始碼:
https://github.com/alexander-uspenskiy/simple-service
依賴關係設置
第 1 步:先決條件
- 安裝 Java 8
- 安裝 Maven
- 安裝 Docker
- 安裝 VS Code 擴充
Mac安裝
# 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安裝
# 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
項目設定(兩個平台)
# Create project structure mkdir -p simple-service cd simple-service
VS 代碼設定
{ "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 Java java -version # Verify Maven mvn -version # Verify Docker docker --version
項目設定
# Create Maven project mvn archetype:generate \ -DgroupId=com.example \ -DartifactId=simple-service \ -DarchetypeArtifactId=maven-archetype-quickstart \ -DarchetypeVersion=1.4 \ -DinteractiveMode=false
建立測試應用程式
最後一步之後,您應該擁有具有預先建置結構的簡單服務目錄。
第 1 步
- 更新 pom.xml 文件
<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>
第 2 步
在 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"); } }
快速解釋:
-
導入與設定
- 使用內建的 com.sun.net.httpserver 套件
- 建立簡單的 HTTP 伺服器,無需外部依賴
- 在連接埠 1800 上運作
伺服器設定
HttpServer.create()
- 建立新的伺服器實例
InetSocketAddress(1800)
- 綁定到連接埠 1800
- 0 - 連接隊列的預設積壓值
- 請求處理
createContext("/")
- 處理所有對根路徑「/」的請求
- Lambda 表達式定義請求處理程序
- 返回「來自 Java 的你好!」滿足所有請求
-
回應流程
- 設定回應代碼 200(確定)
- 設定內容長度
- 將回應位元組寫入輸出流
- 使用 try-with-resources 自動關閉流
伺服器啟動
setExecutor(null)
- 使用預設執行器
server.start()
- 開始監聽請求
- 列印確認訊息
第三步
在專案根目錄建立Dockerfile:
FROM amazoncorretto:8 WORKDIR /app COPY target/simple-service-1.0-SNAPSHOT.jar app.jar EXPOSE 1800 CMD ["java", "-jar", "app.jar"]
步驟 4
建立 docker-compose.yml 來建置容器並將其對應到連接埠 1800
services: app: build: . ports: - "1800:1800" restart: unless-stopped
第 5 步
建立build.sh
#!/bin/bash mvn clean package docker compose build docker compose up
並在終端機中允許此檔案的執行權限:
# 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
建置並執行應用程式
只需運行
# 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
您應該已建置專案、建立映像並執行容器。
要測試應用程序,只需打開瀏覽器,位址為 http://localhost:1800/
快樂編碼!
以上是只需幾分鐘即可使用 Docker 建置和部署您的第一個 Java 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文使用lambda表達式,流API,方法參考和可選探索將功能編程集成到Java中。 它突出顯示了通過簡潔性和不變性改善代碼可讀性和可維護性等好處

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用選擇器和頻道使用單個線程有效地處理多個連接的Java的NIO API,用於非阻滯I/O。 它詳細介紹了過程,好處(可伸縮性,性能)和潛在的陷阱(複雜性,

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文詳細介紹了用於網絡通信的Java的套接字API,涵蓋了客戶服務器設置,數據處理和關鍵考慮因素,例如資源管理,錯誤處理和安全性。 它還探索了性能優化技術,我


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載
最受歡迎的的開源編輯器