Docker 컨테이너를 사용하여 로컬 환경의 포트 1800에서 텍스트를 반환하고 5분 안에 사용할 수 있는 간단한 Java 앱을 만들어 보겠습니다(인터넷 연결 속도에 따라 다름).
내 공개 저장소에서 언제든지 전체 소스 코드를 가져올 수 있습니다.
https://github.com/alexander-uspenskiy/simple-service
종속성 설정
1단계: 전제조건
- Java 8 설치
- 메이븐 설치
- 도커 설치
- VS Code 확장 설치
맥 설치
# 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
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()
- 새 서버 인스턴스 생성
InetSocket주소(1800)
- 포트 1800에 바인딩
- 0 - 연결 대기열의 기본 백로그 값
- 요청 처리
createContext("/")
- 루트 경로 "/"에 대한 모든 요청을 처리합니다
- Lambda 표현식은 요청 핸들러를 정의합니다
- "Hello from Java!"를 반환합니다. 모든 요청에
-
응답 흐름
- 응답 코드를 200(OK)으로 설정
- 콘텐츠 길이 설정
- 출력 스트림에 응답 바이트를 씁니다
- 리소스를 사용해 시도하여 스트림 자동 종료
서버 시작
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
