Docker 컨테이너를 사용하여 로컬 환경의 포트 1800에서 텍스트를 반환하고 5분 안에 사용할 수 있는 간단한 Java 앱을 만들어 보겠습니다(인터넷 연결 속도에 따라 다름).
내 공개 저장소에서 언제든지 전체 소스 코드를 가져올 수 있습니다.
https://github.com/alexander-uspenskiy/simple-service
# 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
# Create project structure mkdir -p simple-service cd simple-service
{ "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단계
<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"); } }
빠른 설명:
가져오기 및 설정
서버 구성
HttpServer.create()
InetSocket주소(1800)
createContext("/")
응답 흐름
서버 시작
setExecutor(null)
server.start()
3단계
프로젝트 루트에 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/
주소에서 브라우저를 열면 됩니다.즐거운 코딩하세요!
위 내용은 Just Inutes에서 Docker를 사용하여 첫 번째 Java 앱 구축 및 배포의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!