将jenkins配置到同一个目录

本文详细介绍如何自定义安装Jenkins,包括配置文件、启动脚本、监听端口等关键设置,以及如何修改目录结构以适应不同需求。通过具体步骤展示如何调整Jenkins的运行环境,确保其稳定运行。

安装包

jenkins-2.204.2-1.1.noarch.rpm

不支持 --prefix指定安装目录

# rpm -ivh jenkins-2.204.2-1.1.noarch.rpm

安装完成后

1、配置文件:/etc/sysconfig/jenkins

2、启动脚本:/etc/init.d/jenkins

3、监听端口:8080

4、war包位置:/usr/lib/jenkins/jenkins.war

5、缓存目录:/var/cache/jenkins

6、安装目录:/var/lib/jenkins

7、日志文件:/var/log/jenkins/jenkins.log

目录修改配置如下:

# mkdir /opt/jenkins

# mkdir /opt/jenkins/logs && mkdir /opt/jenkins/plugins && mkdir /opt/jenkins/conf && mkdir /opt/jenkins/lib && mkdir /opt/jenkins/bin && mkdir /opt/jenkins/home && mkdir /opt/jenkins/cache

分别存放日志、插件、配置文件、war包、启动文件、工作目录、缓存

# mv /etc/sysconfig/jenkins /opt/jenkins/conf && ln -s /opt/jenkins/conf/jenkins /etc/sysconfig/jenkins

# mv /etc/init.d/jenkins /opt/jenkins/bin && ln -s /opt/jenkins/bin/jenkins /etc/init.d/jenkins

# mv /var/lib/jenkins/jenkins.war /opt/jenkins/lib

/opt/jenkins/conf/jenkins修改如下:

## Path:        Development/Jenkins
## Description: Jenkins Automation Server
## Type:        string
## Default:     "/var/lib/jenkins"
## ServiceRestart: jenkins
#
# Directory where Jenkins store its configuration and working
# files (checkouts, build reports, artifacts, ...).
#
JENKINS_HOME="/opt/jenkins/home"

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Java executable to run Jenkins
# When left empty, we'll try to find the suitable Java.
#
JENKINS_JAVA_CMD=""

## Type:        string
## Default:     "jenkins"
## ServiceRestart: jenkins
#
# Unix user account that runs the Jenkins daemon
# Be careful when you change this, as you need to update
# permissions of $JENKINS_HOME and /var/log/jenkins.
#
JENKINS_USER="jenkins"

## Type:        string
## Default: "false"
## ServiceRestart: jenkins
#
# Whether to skip potentially long-running chown at the
# $JENKINS_HOME location. Do not enable this, "true", unless
# you know what you're doing. See JENKINS-23273.
#
#JENKINS_INSTALL_SKIP_CHOWN="false"

## Type: string
## Default:     "-Djava.awt.headless=true"
## ServiceRestart: jenkins
#
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true"

## Type:        integer(0:65535)
## Default:     8080
## ServiceRestart: jenkins
#
# Port Jenkins is listening on.
# Set to -1 to disable
#
JENKINS_PORT="5070"

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# IP address Jenkins listens on for HTTP requests.
# Default is all interfaces (0.0.0.0).
#
JENKINS_LISTEN_ADDRESS=""

## Type:        integer(0:65535)
## Default:     ""
## ServiceRestart: jenkins
#
# HTTPS port Jenkins is listening on.
# Default is disabled.
#
JENKINS_HTTPS_PORT=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Path to the keystore in JKS format (as created by the JDK 'keytool').
# Default is disabled.
#
JENKINS_HTTPS_KEYSTORE=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Password to access the keystore defined in JENKINS_HTTPS_KEYSTORE.
#
JENKINS_HTTPS_KEYSTORE_PASSWORD=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# IP address Jenkins listens on for HTTPS requests.
# Default is disabled.
#
JENKINS_HTTPS_LISTEN_ADDRESS=""

## Type:        integer(0:65535)
## Default:     ""
## ServiceRestart: jenkins
#
# HTTP2 port Jenkins is listening on.
# Default is disabled.
#
# Notice: HTTP2 support may require additional configuration, see Winstone
# documentation for more information.
#
JENKINS_HTTP2_PORT=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# IP address Jenkins listens on for HTTP2 requests.
# Default is disabled.
#
# Notice: HTTP2 support may require additional configuration, see Winstone
# documentation for more information.
#
JENKINS_HTTP2_LISTEN_ADDRESS=""

## Type:        integer(1:9)
## Default:     5
## ServiceRestart: jenkins
#
# Debug level for logs -- the higher the value, the more verbose.
# 5 is INFO.
#
#
JENKINS_DEBUG_LEVEL="5"

## Type:        yesno
## Default:     no
## ServiceRestart: jenkins
#
# Whether to enable access logging or not.
#
JENKINS_ENABLE_ACCESS_LOG="no"

## Type:        integer
## Default:     100
## ServiceRestart: jenkins
#
# Maximum number of HTTP worker threads.
#
JENKINS_HANDLER_MAX="100"

## Type:        integer
## Default:     20
## ServiceRestart: jenkins
#
# Maximum number of idle HTTP worker threads.
#
JENKINS_HANDLER_IDLE="20"

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Folder for additional jar files to add to the Jetty class loader.
# See Winstone documentation for more information.
# Default is disabled.
#
JENKINS_EXTRA_LIB_FOLDER=""

## Type:        string
## Default:     ""
## ServiceRestart: jenkins
#
# Pass arbitrary arguments to Jenkins.
# Full option list: java -jar jenkins.war --help
#
JENKINS_ARGS=""

/opt/jenkins/bin/jenkins修改如下:

JENKINS_WAR="/opt/jenkins/lib/jenkins.war"
test -r "$JENKINS_WAR" || { echo "$JENKINS_WAR not installed";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 5; fi; }

# Check for existence of needed config file and read it
JENKINS_CONFIG=/opt/jenkins/conf/jenkins
test -e "$JENKINS_CONFIG" || { echo "$JENKINS_CONFIG not existing";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 6; fi; }
test -r "$JENKINS_CONFIG" || { echo "$JENKINS_CONFIG not readable. Perhaps you forgot 'sudo'?";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 6; fi; }

JENKINS_PID_FILE="/var/run/jenkins.pid"
JENKINS_LOCKFILE="/var/lock/subsys/jenkins"

# Source function library.
. /etc/init.d/functions

# Read config
[ -f "$JENKINS_CONFIG" ] && . "$JENKINS_CONFIG"

# Set up environment accordingly to the configuration settings
[ -n "$JENKINS_HOME" ] || { echo "JENKINS_HOME not configured in $JENKINS_CONFIG";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 6; fi; }
[ -d "$JENKINS_HOME" ] || { echo "JENKINS_HOME directory does not exist: $JENKINS_HOME";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 1; fi; }

# Search usable Java as /usr/bin/java might not point to minimal version required by Jenkins.
# see http://www.nabble.com/guinea-pigs-wanted-----Hudson-RPM-for-RedHat-Linux-td25673707.html
candidates="
/usr/local/share/jdk1.8.0_231/bin/java
"

for candidate in $candidates
do
  [ -x "$JENKINS_JAVA_CMD" ] && break
  JENKINS_JAVA_CMD="$candidate"
done


JAVA_CMD="$JENKINS_JAVA_CMD $JENKINS_JAVA_OPTIONS -DJENKINS_HOME=$JENKINS_HOME -jar $JENKINS_WAR"
PARAMS="--logfile=/opt/jenkins/logs/jenkins.log --webroot=/opt/jenkins/cache/war --daemon"
[ -n "$JENKINS_PORT" ] && PARAMS="$PARAMS --httpPort=$JENKINS_PORT"
[ -n "$JENKINS_LISTEN_ADDRESS" ] && PARAMS="$PARAMS --httpListenAddress=$JENKINS_LISTEN_ADDRESS"
[ -n "$JENKINS_HTTPS_PORT" ] && PARAMS="$PARAMS --httpsPort=$JENKINS_HTTPS_PORT"
[ -n "$JENKINS_HTTPS_KEYSTORE" ] && PARAMS="$PARAMS --httpsKeyStore=$JENKINS_HTTPS_KEYSTORE"
[ -n "$JENKINS_HTTPS_KEYSTORE_PASSWORD" ] && PARAMS="$PARAMS --httpsKeyStorePassword='$JENKINS_HTTPS_KEYSTORE_PASSWORD'"
[ -n "$JENKINS_HTTPS_LISTEN_ADDRESS" ] && PARAMS="$PARAMS --httpsListenAddress=$JENKINS_HTTPS_LISTEN_ADDRESS"
[ -n "$JENKINS_HTTP2_PORT" ] && PARAMS="$PARAMS --http2Port=$JENKINS_HTTP2_PORT"
[ -n "$JENKINS_HTTP2_LISTEN_ADDRESS" ] && PARAMS="$PARAMS --http2ListenAddress=$JENKINS_HTTP2_LISTEN_ADDRESS"
[ -n "$JENKINS_DEBUG_LEVEL" ] && PARAMS="$PARAMS --debug=$JENKINS_DEBUG_LEVEL"
[ -n "$JENKINS_HANDLER_STARTUP" ] && PARAMS="$PARAMS --handlerCountStartup=$JENKINS_HANDLER_STARTUP"
[ -n "$JENKINS_HANDLER_MAX" ] && PARAMS="$PARAMS --handlerCountMax=$JENKINS_HANDLER_MAX"
[ -n "$JENKINS_HANDLER_IDLE" ] && PARAMS="$PARAMS --handlerCountMaxIdle=$JENKINS_HANDLER_IDLE"
[ -n "$JENKINS_EXTRA_LIB_FOLDER" ] && PARAMS="$PARAMS --extraLibFolder=$JENKINS_EXTRA_LIB_FOLDER"
[ -n "$JENKINS_ARGS" ] && PARAMS="$PARAMS $JENKINS_ARGS"

if [ "$JENKINS_ENABLE_ACCESS_LOG" = "yes" ]; then
    PARAMS="$PARAMS --accessLoggerClassName=winstone.accesslog.SimpleAccessLogger --simpleAccessLogger.format=combined --simpleAccessLogger.file=/opt/jenkins/logs/access_log"
fi

RETVAL=0

case "$1" in
    start)
        echo -n "Starting Jenkins "
        daemon --user "$JENKINS_USER" --pidfile "$JENKINS_PID_FILE" $JAVA_CMD $PARAMS > /dev/null
        RETVAL=$?
        if [ $RETVAL = 0 ]; then
            success
            echo > "$JENKINS_PID_FILE"  # just in case we fail to find it
            MY_SESSION_ID=`/bin/ps h -o sess -p $$`
            # get PID
            /bin/ps hww -u "$JENKINS_USER" -o sess,ppid,pid,cmd | \
            while read sess ppid pid cmd; do
                [ "$ppid" = 1 ] || continue
                # this test doesn't work because Jenkins sets a new Session ID
                # [ "$sess" = "$MY_SESSION_ID" ] || continue
                echo "$cmd" | grep $JENKINS_WAR > /dev/null
                [ $? = 0 ] || continue
                # found a PID
                echo $pid > "$JENKINS_PID_FILE"
            done
            touch $JENKINS_LOCKFILE
        else
            failure
        fi
        echo
        ;;
    stop)
        echo -n "Shutting down Jenkins "
        killproc jenkins
        rm -f $JENKINS_LOCKFILE
        RETVAL=$?
        echo
        ;;
    try-restart|condrestart)
        if test "$1" = "condrestart"; then
                echo "${attn} Use try-restart ${done}(LSB)${attn} rather than condrestart ${warn}(RH)${norm}"
        fi
        $0 status
        if test $? = 0; then
                $0 restart
        else
                : # Not running is not a failure.
        fi
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    force-reload)
        echo -n "Reload service Jenkins "
        $0 try-restart
        ;;
    reload)
        $0 restart
        ;;
    status)
        status jenkins
        RETVAL=$?
        ;;
    probe)
        ## Optional: Probe for the necessity of a reload, print out the
        ## argument to this init script which is required for a reload.
        ## Note: probe is not (yet) part of LSB (as of 1.9)

        test "$JENKINS_CONFIG" -nt "$JENKINS_PID_FILE" && echo reload
        ;;
    *)
        echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|probe}"
        exit 1
        ;;
esac
exit $RETVAL

最后一步,修改/opt/jenkins目录所有者授权:

# userdel -rf jenkins && useradd -g root -m jenkins

# chown -R jenkins:root /opt/jenkins

否则jenkins启动不成功

# systemctl enable jenkins.service

# systemctl start jenkins.service

最后,启动jenkins成功,日志显示如下:

Running from: /opt/jenkins/lib/jenkins.war
2020-02-02 14:54:20.093+0000 [id=1]     WARNING winstone.Logger#logInternal: Parameter handlerCountMax is now deprecated
2020-02-02 14:54:20.094+0000 [id=1]     WARNING winstone.Logger#logInternal: Parameter handlerCountMaxIdle is now deprecated
2020-02-02 14:54:20.101+0000 [id=1]     INFO    org.eclipse.jetty.util.log.Log#initialized: Logging initialized @512ms to org.eclipse.jetty.util.log.JavaUtilLog
2020-02-02 14:54:20.154+0000 [id=1]     INFO    winstone.Logger#logInternal: Beginning extraction from war file
2020-02-02 14:54:21.353+0000 [id=1]     WARNING o.e.j.s.handler.ContextHandler#setContextPath: Empty contextPath
2020-02-02 14:54:21.409+0000 [id=1]     INFO    org.eclipse.jetty.server.Server#doStart: jetty-9.4.z-SNAPSHOT; built: 2019-05-02T00:04:53.875Z; git: e1bc35120a6617ee3df052294e433f3a25ce7097; jvm 1.8.0_231-b11
2020-02-02 14:54:21.673+0000 [id=1]     INFO    o.e.j.w.StandardDescriptorProcessor#visitServlet: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
2020-02-02 14:54:21.724+0000 [id=1]     INFO    o.e.j.s.s.DefaultSessionIdManager#doStart: DefaultSessionIdManager workerName=node0
2020-02-02 14:54:21.724+0000 [id=1]     INFO    o.e.j.s.s.DefaultSessionIdManager#doStart: No SessionScavenger set, using defaults
2020-02-02 14:54:21.726+0000 [id=1]     INFO    o.e.j.server.session.HouseKeeper#startScavenging: node0 Scavenging every 600000ms
2020-02-02 14:54:22.105+0000 [id=1]     INFO    hudson.WebAppMain#contextInitialized: Jenkins home directory: /opt/jenkins/home found at: SystemProperties.getProperty("JENKINS_HOME")
2020-02-02 14:54:22.195+0000 [id=1]     INFO    o.e.j.s.handler.ContextHandler#doStart: Started w.@5b800468{Jenkins v2.204.2,/,file:///opt/jenkins/cache/war/,AVAILABLE}{/opt/jenkins/cache/war}
2020-02-02 14:54:22.211+0000 [id=1]     INFO    o.e.j.server.AbstractConnector#doStart: Started ServerConnector@46d59067{HTTP/1.1,[http/1.1]}{0.0.0.0:5070}
2020-02-02 14:54:22.211+0000 [id=1]     INFO    org.eclipse.jetty.server.Server#doStart: Started @2623ms
2020-02-02 14:54:22.212+0000 [id=22]    INFO    winstone.Logger#logInternal: Winstone Servlet Engine v4.0 running: controlPort=disabled
2020-02-02 14:54:23.509+0000 [id=29]    INFO    jenkins.InitReactorRunner$1#onAttained: Started initialization
2020-02-02 14:54:23.534+0000 [id=31]    INFO    jenkins.InitReactorRunner$1#onAttained: Listed all plugins
2020-02-02 14:54:24.904+0000 [id=32]    INFO    jenkins.InitReactorRunner$1#onAttained: Prepared all plugins
2020-02-02 14:54:24.913+0000 [id=28]    INFO    jenkins.InitReactorRunner$1#onAttained: Started all plugins
2020-02-02 14:54:24.927+0000 [id=31]    INFO    jenkins.InitReactorRunner$1#onAttained: Augmented all extensions
2020-02-02 14:54:25.899+0000 [id=31]    INFO    jenkins.InitReactorRunner$1#onAttained: Loaded all jobs
2020-02-02 14:54:25.955+0000 [id=47]    INFO    hudson.model.AsyncPeriodicWork#lambda$doRun$0: Started Download metadata
2020-02-02 14:54:25.979+0000 [id=47]    INFO    hudson.util.Retrier#start: Attempt #1 to do the action check updates server
2020-02-02 14:54:26.978+0000 [id=27]    INFO    o.s.c.s.AbstractApplicationContext#prepareRefresh: Refreshing org.springframework.web.context.support.StaticWebApplicationContext@1dd3299c: display name [Root WebApplicationContext]; startup date [Sun Feb 02 22:54:26 CST 2020]; root of context hierarchy
2020-02-02 14:54:26.979+0000 [id=27]    INFO    o.s.c.s.AbstractApplicationContext#obtainFreshBeanFactory: Bean factory for application context [org.springframework.web.context.support.StaticWebApplicationContext@1dd3299c]: org.springframework.beans.factory.support.DefaultListableBeanFactory@750fec9
2020-02-02 14:54:26.988+0000 [id=27]    INFO    o.s.b.f.s.DefaultListableBeanFactory#preInstantiateSingletons: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@750fec9: defining beans [authenticationManager]; root of factory hierarchy
2020-02-02 14:54:27.163+0000 [id=27]    INFO    o.s.c.s.AbstractApplicationContext#prepareRefresh: Refreshing org.springframework.web.context.support.StaticWebApplicationContext@59998532: display name [Root WebApplicationContext]; startup date [Sun Feb 02 22:54:27 CST 2020]; root of context hierarchy
2020-02-02 14:54:27.164+0000 [id=27]    INFO    o.s.c.s.AbstractApplicationContext#obtainFreshBeanFactory: Bean factory for application context [org.springframework.web.context.support.StaticWebApplicationContext@59998532]: org.springframework.beans.factory.support.DefaultListableBeanFactory@35d648d8
2020-02-02 14:54:27.164+0000 [id=27]    INFO    o.s.b.f.s.DefaultListableBeanFactory#preInstantiateSingletons: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@35d648d8: defining beans [filter,legacy]; root of factory hierarchy
2020-02-02 14:54:27.401+0000 [id=27]    INFO    jenkins.install.SetupWizard#init:

*************************************************************
*************************************************************
*************************************************************

Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:

3d95c109a3564327b9411a0d153c7f76

This may also be found at: /opt/jenkins/home/secrets/initialAdminPassword

浏览器打开:http://localhost:5070 进行初始化和安装配置

这样就可以实现将/opt/jenkins目录打包方便移植

### 配置 JenkinsJENKINS_HOME 目录 为了在 Jenkins配置 `JENKINS_HOME` 目录,可以通过以下方法实现: #### 方法一:通过 Tomcat 环境变量配置 如果 Jenkins 是部署在 Apache Tomcat 上,则可以在 Tomcat 的环境变量中设置 `JENKINS_HOME`。具体操作如下: 1. 创建一个新的目录作为 Jenkins 的工作目录,例如 `/var/lib/jenkins_home`[^1]。 2. 编辑 Tomcat 的启动脚本(通常位于 `$CATALINA_BASE/bin/setenv.sh` 或者 Windows 下的 `setenv.bat` 文件),并添加以下内容: ```bash export JENKINS_HOME=/var/lib/jenkins_home ``` 3. 重启 Tomcat 服务以使更改生效。 这样,Jenkins 将会使用指定的路径来存储其数据和配置文件。 #### 方法二:通过操作系统级别的环境变量 除了在 Tomcat 中配置外,还可以直接在系统的全局环境中定义 `JENKINS_HOME` 变量。对于 Linux 和 macOS 用户来说,可以编辑 `.bashrc` 或 `.zshrc` 文件;而对于 Windows 用户则需要进入系统属性 -> 高级系统设置 -> 环境变量页面完成此操作。以下是针对不同平台的具体命令示例: - **Linux/macOS** ```bash echo 'export JENKINS_HOME="/path/to/custom/directory"' >> ~/.bashrc && source ~/.bashrc ``` - **Windows PowerShell** ```powershell [System.Environment]::SetEnvironmentVariable('JENKINS_HOME', 'C:\custom\directory', [System.EnvironmentVariableTarget]::Machine) ``` 完成后重新加载 shell 或登录到新的终端窗口即可应用修改后的值[^4]。 #### 方法三:Pipeline 脚本中的动态调整 (仅限于特定场景下的临时覆盖) 虽然不推荐长期依赖这种方式来进行主要的工作区管理,但在某些特殊情况下可能需要用到它——比如测试不同的构建上下文中切换行为等。下面是一个简单的 Groovy Pipeline 片段展示如何打印当前使用的 HOME 值以及尝试改变默认位置的行为: ```groovy pipeline { agent any stages { stage('Example') { steps{ script{ // 打印原始状态 println "Original JENKINS_HOME is set to: ${env.JENKINS_HOME}" withEnv(['JENKINS_HOME=/tmp/new_jenkins_home']){ // 测试新设定的效果 println "Inside block, changed JENKINS_HOME now points at: ${env.JENKINS_HOME}" dir('/tmp/new_jenkins_home'){ writeToFile text:"Test file created by job.", file:'testfile.txt' } } // 复原后确认恢复情况 println "After exiting scope, back to original setting?: ${env.JENKINS_HOME}" } } } } } ``` 注意这种方法只适用于个别任务期间局部范围内的变更,并不会影响整个服务器层面的基础架构布局决策[^3]。 --- ### 注意事项 - 如果未正确配置 `JENKINS_HOME` 导致找不到初始管理员密码的位置,请检查实际生成的日志消息里提到的确切地址是否一致[^4]。 - 当存在多个 JDK 安装实例时,还需要额外关注 `JAVA_HOME` 参数指向哪一套工具链版本被选用执行相关插件功能逻辑运算过程之中[^2]。
评论 10
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值