如何减少Docker中的Spring Boot应用程序内存使用率?

Вяч*_*лав 2 java docker dockerfile

我有一个问题,为什么非常简单的Spring Boot应用程序会分配100 MB RAM?如何减少内存使用量?

1)https://start.spring.io/生成具有“ Spring Web Starter”依赖项的演示程序

2)Dockerfile

FROM openjdk:8-jre-alpine
ADD /target/demo.jar demo.jar
EXPOSE 8080
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar /demo.jar"]
Run Code Online (Sandbox Code Playgroud)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
    <finalName>demo</finalName>
</build>
Run Code Online (Sandbox Code Playgroud)

班级

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/app")
public class AppRestController {
    @GetMapping(value = "/test")
    public ResponseEntity<String> health() {
        return new ResponseEntity<>("test OK!", HttpStatus.OK);
    }
}
Run Code Online (Sandbox Code Playgroud)

1)内存测试1

docker build -f dockerfile -t演示

docker run -p 8080:8080演示

码头工人统计

内存使用量/限制
101.5MiB / 989.4MiB

2)使用JVM键的内存测试2

码头工人停止dc9305c42d09

docker run -p 8080:8080 -e JAVA_OPTS =“-Xmx50M -Xms50M”演示

码头工人统计

内存使用量/限制107.2MiB / 989.4MiB

内存使用情况相同。我该如何减少呢?

小智 5

您需要传递-m 50m之类的东西来限制容器可用的内存,同时传递-Xmx和Xms for JVM。

以下文章对此进行了很好的解释。

Docker容器中的JVM内存分配