Tag Archives: spring boot

Containerize Spring Boot App with Docker

  • Add docker maven plugin to pom.xml
<plugin>
            <groupId>com.spotify</groupId>
            <artifactId>dockerfile-maven-plugin</artifactId>
            <version>1.4.0</version>
            <configuration>
                <repository>${docker.image.prefix}/${project.artifactId}</repository>
                <buildArgs>
                    <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
                </buildArgs>
            </configuration>
</plugin>
  • Create Dockerfile at the root of the project
FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
  • Build docker image

mvn clean install dockerfile:build

  • Login to docker hub and push the image to docker hub (Optional Step)

docker login -u <username>
mvn dockerfile:push

  • Verify the image is built and available

docker images

  • Run Spring Boot App from docker

docker run –rm -d –restart -p 8080:8080 ${docker.image.prefix}/${project.artifactId}

Upload MultipartFile using Spring RestTemplate

public boolean uploadAttachment(MultipartFile file) {
        boolean success = false;
        if (!file.isEmpty()) {
            try {
                ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
                    @Override
                    public String getFilename() {
                        return file.getOriginalFilename();
                    }
                };
                LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
                map.add("file", fileAsResource);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
                String url = "http://localhost:8084/attachments";

                ResponseEntity<String> response = restTemplate.exchange(url,
                        HttpMethod.POST,
                        entity,
                        String.class);
                if (response.getStatusCode().equals(HttpStatus.OK)) {
                    success = true;
                }
            } catch (Exception e) {
                LOGGER.error("Failed to upload attachment", e);
            }
        }
        return success;
    }