Jenkins构建失败:无法创建/var/lib/tomcat8/.m2目录求助
Hey there! Let's break down why this error is happening and walk through the fixes step by step.
Root Cause
This error pops up because the user running your Jenkins instance doesn’t have write permissions to create the .m2 directory inside /var/lib/tomcat8. If Jenkins is deployed as a WAR file in Tomcat, it’s likely running under the tomcat8 user—but sometimes directory permissions or SELinux policies block write access even for the owner.
Solution 1: Verify and Fix Directory Permissions
First, let’s confirm the basics:
Check the owner and permissions of
/var/lib/tomcat8:ls -ld /var/lib/tomcat8You should see output like
drwxr-xr-x 5 tomcat8 tomcat8 4096 Aug 10 12:00 /var/lib/tomcat8(owner/group istomcat8).If Jenkins is running under a different user (e.g.,
jenkins), add that user to thetomcat8group and grant write access to the directory:# Add jenkins user to tomcat8 group sudo usermod -aG tomcat8 jenkins # Grant group write permissions to the directory sudo chmod g+w /var/lib/tomcat8 # Restart Jenkins to apply the group change sudo systemctl restart jenkinsIf Jenkins is running under
tomcat8(common when deployed in Tomcat), ensure the user has write access to its own home directory:sudo chmod u+w /var/lib/tomcat8
Solution 2: Use a Custom Maven Repository (Recommended)
Instead of modifying Tomcat’s directory permissions (which can introduce security risks), configure Maven to use a directory Jenkins has full access to:
- In Jenkins, go to Manage Jenkins > Global Tool Configuration.
- Find your Maven installation, and add the following to MAVEN_OPTS:
(The-Dmaven.repo.local=/var/lib/jenkins/.m2/repository/var/lib/jenkinsdirectory is owned by the Jenkins user by default, so this should work out of the box.) - Save the configuration and re-run your build.
Alternatively, you can specify this directly in your Jenkins project’s build step:
- In the Goals and options field, add:
Just make sureclean install -Dmaven.repo.local=/path/to/your/custom/repo/path/to/your/custom/repois a directory the Jenkins user can write to.
Solution 3: Check SELinux (For RHEL/CentOS/Rocky Linux)
If you’re on a system with SELinux enabled, it might be blocking the write operation even if file permissions are correct:
- Check SELinux status:
If it showssestatusCurrent mode: enforcing, temporarily disable it to test:sudo setenforce 0 - Re-run your build. If it works, create a permanent SELinux policy to allow write access to
.m2:# Add SELinux context for the .m2 directory sudo semanage fcontext -a -t tomcat_home_t "/var/lib/tomcat8/.m2(/.*)?" # Apply the context sudo restorecon -Rv /var/lib/tomcat8/.m2 # Re-enable SELinux if needed sudo setenforce 1
内容的提问来源于stack exchange,提问作者MPK

