使用 Java 和带有 CodeArtifact 依赖项的 Maven 构建 Dockerfile

问题描述 投票:0回答:1

我正在尝试使用 Docker 构建我的项目,它有一些 Java REST API,我在多服务架构上使用 Maven 和 Spring Boot。我有一个名为“common-utilities”的“从属”模块,它具有我需要的所有通用实体和一些日历实用程序,并且该模块用作我所有其他模块的依赖项。

我遇到了一个问题,Docker 无法构建,因为它找不到我自己的从属模块作为另一个模块的依赖项,因为它正在 Maven Central 上查找它,经过一些搜索后,我发现我可以手动将此依赖项的

.jar
复制到 docker build 的
.m2
文件夹,但是对该解决方案不满意。然后我发现我可以将从属模块的
.jar
上传到私有存储库,尝试了 Nexus,但由于我很快就会使用 AWS,所以我转向了 AWS Code Artifact。

现在的问题是,如何从 AWS 基础设施外部设置我的

settings.xml
需要下载此依赖项的令牌?

java xml docker maven
1个回答
0
投票

经过大量搜索后,我找到了一种方法来做到这一点。我尝试了

RUN
命令,但由于它的执行无法将结果保存到可用变量中以供
settings.xml
捕获,所以我不得不采取另一种方法。 这是我的 Dockerfile:

###############################################################
# Build stage
# Maven image to build the application
FROM maven:3.9.6-amazoncorretto-17-al2023 AS build-stage

# Creating the directory
RUN mkdir -p /usr/src/app
# Setting the working directory.
WORKDIR /usr/src/app
# Adding the source code to the build stage.
ADD . /usr/src/app

# And here comes the Amazon configuration step!
RUN yum install aws-cli -y
RUN aws configure set aws_access_key_id 'YOUR KEY'
RUN aws configure set aws_secret_access_key 'YOUR SECRET ACCESS KEY'
RUN aws configure set aws_region 'YOUR REGION'
RUN aws configure set aws_output_format json

# Then I execute the command to get Code Artifact's token and save it into a file called "result" located in "./"
RUN aws codeartifact get-authorization-token --domain YOUR-DOMAIN --domain-owner YOUR-OWNER-ID --region YOUR-REGION --query authorizationToken --output text >> ./result

# So now I execute the maven install command passing the settings.xml WITH the property "token", which is a cat command to read from the file that has the token and to be used inside the XML file.
RUN mvn -Dtoken=${cat ./result} -s settings.xml install -U

###############################################################
# Production step. Now it's done, it works!
FROM openjdk:17-alpine AS production-stage
COPY --from=build-stage /usr/src/app/target/*.jar my-api.jar
EXPOSE 8788
ENTRYPOINT ["java", "-Dspring.profiles.active=prod", "-Xmx256m", "-Xms128m", "-jar", "my-api.jar"]

这是我的

settings.xml

<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 
https://maven.apache.org/xsd/settings-1.2.0.xsd">
<servers>
  <server>
    <id>domain-name</id>
    <username>aws</username>
    <password>${token}</password>
  </server>
</servers>

<profiles>
  <profile>
  <id>domain-name</id>
  <activation>
  <activeByDefault>true</activeByDefault>
  </activation>
    <repositories>
      <repository>
           <id>domain-name</id>
           <url>repo-url</url>
      </repository>
    </repositories>
  </profile>
</profiles>
</settings>

我不确定这是否是正确的方法,但它有效!所以我想与你们分享这个信息,因为我无法找到任何关于如何做到这一点的信息。

© www.soinside.com 2019 - 2024. All rights reserved.