前置条件: 安装docker
参考: Jenkins官方安装文档
1 安装docker:dind
shell
docker run \
--name jenkins-docker \
--rm \
--detach \
--privileged \
--network jenkins \
--network-alias docker \
--env DOCKER_TLS_CERTDIR=/certs \
--volume jenkins-docker-certs:/certs/client \
--volume jenkins-data:/var/jenkins_home \
--publish 2376:2376 \
docker:dind \
--storage-driver overlay2
2 通过Dockerfile安装Jenkins
dockerfile
FROM jenkins/jenkins:2.452.3-jdk17
USER root
RUN apt-get update && apt-get install -y lsb-release
RUN curl -fsSLo /usr/share/keyrings/docker-archive-keyring.asc \
http://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg
RUN echo "deb [arch=$(dpkg --print-architecture) \
signed-by=/usr/share/keyrings/docker-archive-keyring.asc] \
http://mirrors.aliyun.com/docker-ce/linux/debian \
$(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list
RUN apt-get update && apt-get install -y docker-ce-cli
USER jenkins
RUN jenkins-plugin-cli --plugins "blueocean docker-workflow"
3 构建
shell
docker build -t myjenkins-blueocean:2.452.3-1 .
4 运行镜像
shell
docker run \
--name jenkins-blueocean \
--restart=on-failure \
--detach \
--network jenkins \
--env DOCKER_HOST=tcp://docker:2376 \
--env DOCKER_CERT_PATH=/certs/client \
--env DOCKER_TLS_VERIFY=1 \
--publish 8080:8080 \
--publish 50000:50000 \
--volume jenkins-data:/var/jenkins_home \
--volume jenkins-docker-certs:/certs/client:ro \
myjenkins-blueocean:2.452.3-1
5 访问web页面
shell
# 非Docker安装方式获取初始解锁密码
cat /var/lib/jenkins/secrets/initialAdminPassword
# Docker安装方式获取初始解锁密码, 注意替换容器id或名称
docker exec ${CONTAINER_ID or CONTAINER_NAME} cat /var/jenkins_home/secrets/initialAdminPassword
# 访问`ip:8080`, 输入密码, 创建管理员账户, 安装推荐插件
# 安装插件Role-based Authorization Strategy(管理Jenkins用户权限)和Publish Over SSH(通过SSH发送文件并执行命令)
6 配置Git
shell
# 进入容器
docker exec -it jenkins-blueocean bash
# 生成public key, 会提示生成位置
ssh-keygen -t ed25519 -C "your_email@example.com"
cd /var/jenkins_home/.ssh/
cat id_ed25519.pub
# 将得到的文本公钥(SSH Key)添加到github或gitlab中