欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GitLab Runner Maven Docker环境的应用

程序员文章站 2022-06-11 19:05:07
...

背景

Maven可作为Java的构建环境,当Maven构建打包时,在本地会创建一个本地仓库存放所以的依赖包,Runner运行在Docker中时,仓库地址是在Docker容器中,当Docker容器重启时则创建一个新的容器,原Docker中下载好的Maven依赖包全部都会丢失,所以我们将容器中的仓库地址映射到宿主机上避免上述情况反生。

Maven仓库映射到宿主机

GitLab Runner运行之后在config目录下会生成config.toml文件,修改文件里的volumes属性字段,将Docker里Maven仓库地址映射到宿主机上,如下:

concurrent = 1
check_interval = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = "my-runner"
  url = "http://xxx.xxx.xxx.xxx/"
  token = "xxxxxxxxx-"
  executor = "docker"
  [runners.custom_build_dir]
  [runners.docker]
    tls_verify = false
    image = "maven:3-jdk-8"
    privileged = false
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/cache","/data/maven/repository/:/root/.m2/repository:rw","/data/maven:/usr/share/maven:rw"]
    shm_size = 0
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]

在配置中/data/maven/repository/:/root/.m2/repository:rw将Docker容器中仓库地址/root/.m2/repository映射到宿主机的/data/maven/repository/的目录。

/data/maven:/usr/share/maven:rw将Maven环境映射到宿主机上。

Maven上传包到远程仓库

Maven需要修改setting.xml文件,如下:

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

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>F:\work\maven_repo</localRepository>
  
  <pluginGroups>
  </pluginGroups>

  <proxies>
  </proxies>

  <servers>
	<server>
      <id>nexus</id>
      <username>repo</username>
      <password>123456</password>
    </server>
	
    <!-- id与pom.xml关联的私服id相同 -->
	<server>
      <id>nexus-releases</id>
      <username>repo</username>
      <password>123456</password>
    </server>
	
	<server>
      <id>nexus-snapshots</id>
      <username>repo</username>
      <password>123456</password>
    </server>
	
  </servers>

  <mirrors>
	<mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://182.61.31.101:8081/repository/maven-public/</url>
    </mirror>
  </mirrors>

  <profiles>   
  </profiles>

</settings>

如果自己工程编译成jar后需要上传到Maven私服需要在pom.xml中添加如下配置:

<distributionManagement>
        <repository>
            <!-- id与maven settings.xml中设置权限的id相同 -->
            <id>nexus-releases</id>
            <name>Internal Releases</name>
            <url>http://182.61.31.101:8081/repository/maven-releases/</url>
        </repository>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>Internal Snapshots</name>
            <url>http://182.61.31.101:8081/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

其中repository和snapshotRepository中的id值需要与setting.xml中server的id一致,否则会出现权限认证错误

打包镜像并上传到远程镜像仓库